在响应式表单中未选择Angular 6的默认值

时间:2019-02-23 18:59:32

标签: angular typescript angular-reactive-forms

我有一个如下所示的表格。并将区域下拉列表的默认值设置为“ ALL”,并通过api调用填充其他值。

 <form method="POST" for enctype="multipart/form-data" [formGroup]="unitSearchForm">
            <div class="form-group">
              <label for="Zone">Zone</label>
              <select class="form-control" id="zone" formControlName="zoneId">
                <option [ngValue]="0">All</option>
                <option [ngValue]="zone.ZoneId" *ngFor="let zone of (_zones|async)?.Result">{{ zone.ZoneName}}</option>
              </select>
            </div>
            <div class="form-group">
              <input class="form-control" type="text" id="search" formControlName="unitName"
                placeholder="Search by Unit Name" />
            </div>
            <div class="form-group">
              <select class="form-control" formControlName="status">
                <option [ngValue]="status.Code" *ngFor="let status of _statusArr">{{status.Name}}</option>
              </select>
            </div>
            <div class="align-self-end form-group">
              <button type="submit" class="btn  btn-primary" (click)="SearchUnits()"><i
                  class="fa fa-fw fa-search"></i>Search</button>
            </div>
          </form>

/*
Component Code
*/

      ngOnInit() {
        this.InitilizeSearchForm();
        this.InitilizeSelectors();
      }


      private InitilizeSearchForm() {
        this.unitSearchForm = this._fb.group({
          zoneId: ['0'],
          unitName:['',Validators.maxLength(100)],
          status:['A']
        });
      }

      private InitilizeSelectors(){
        let searchCriteria: IDictionary = {}
        this._statusArr=this._dataservice.GetStatus();
        this._zones = this._adminService.Getzones(searchCriteria);
        searchCriteria["status"] =  this.unitSaveForm.get('status').value;
      }

如何在区域下拉列表中选择“全部”?初始化表单时,我尝试设置该值。但这是行不通的。始终第一个选择的值是空。

1 个答案:

答案 0 :(得分:0)

您可以将[value]绑定用于选项,将[selected]绑定用于All选项:

<div class="form-group">
  <label for="Zone">Zone</label>
  <select class="form-control" id="zone" formControlName="zoneId">
    <option value="All" [selected]="'All'">All</option>
    <option [value]="zone.ZoneId" *ngFor="let zone of (_zones|async)?.Result">{{ zone.ZoneName}}
    </option>
  </select>
</div>

选中stackblitz