Angular 6选择默认值不起作用

标签 angular angular6

我有一个带有默认选定禁用值的选择下拉列表,以及从后端加载的地区列表。我的问题是下拉列表从不显示所选值,始终显示空白。

<form [formGroup]="districtForm">
  District:
  <select formControlName="districtControl" (change)="filterBuildings($event.target.value)" [value]='' class="form-control">
    <option value="" disabled selected>Please select district</option>
    <option *ngFor="let district of districts" [ngValue]="district">
      {{district.districtName}}
    </option>
  </select>
  <div *ngIf="errorMessageDistrict" class="text-danger">District is required
  </div>
</form>

这是我的 ts 代码:

import { Component } from '@angular/core';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
import { InfoService } from '../../services/info.service';
import { first } from 'rxjs/operators';
import { District } from '../../models/district';
import { FormGroup, FormControl, FormBuilder } from '@angular/forms';

@Component({
  selector: 'app-school-switch',
  templateUrl: './school-switch.component.html',
  styleUrls: ['./school-switch.component.scss']
})
export class SchoolSwitchComponent {
  districts: District[] = [];
  selectedDistrict: District;
  errorMessageDistrict;
  firstDistrict: any;
  districtForm = new FormGroup({
    districtControl: new FormControl()
  });

  constructor(
    public activeModal: NgbActiveModal,
    private infoService: InfoService,
    private fb: FormBuilder
  ) {}

  ngOnInit() {
    this.infoService
      .getDistricts()
      .pipe(first())
      .subscribe(districts => {
        this.districts = districts;
      });
  }

  filterBuildings(filterVal: any) {
      this.selectedDistrict = this.districtForm.value.districtControl;
      //some more code
  }

最佳答案

通常我在 ngOnInit 中创建 FormGroup,然后在其中定义默认值,如下所示:

import { FormGroup, FormBuilder, Validators } from '@angular/forms';

constructor(private formBuilder: FormBuilder){
}

ngOnInit(){
      this.districtForm = this.formBuilder.group({
        districtControl: ['myDefaultValue', Validators.required]
      });
}

关于Angular 6选择默认值不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52370006/

相关文章:

在 Web Worker 中导入 tensorflow 时出现 Angular typescript 类型检查问题

html - 根据 Angular 4 中的屏幕大小更改内容的显示方式

typescript - 如何在 Angular 6+ 的 mat-paginator 中更改 itemsPerPageLabel

angular5 - Angular 5/6项目查询参数加密

angular - 表单数组中的动态垫选择选项

angular - 创建类以在 Angular 4 中保存所有自定义验证的正确方法

php - 在 Laravel 和 Angular 项目中分离 AngularJS Controller 文件

angular6 - 日历在第一次加载时不显示事件,仅在触发窗口中的任何元素后显示

angular - 如果@Input正在接收对象,则ngOnChanges不触发

typescript - 如何将语法 "inputs"属性更改为 "@Input"属性装饰器