Angular Reactive forms 选择默认对象

Joh*_*ohn 1 reactive-forms angular angular-reactive-forms

我正在使用反应式表单,并且我有一个来自对象数组的选择框。我试图设置默认值,但它只是没有设置。

我的表格:

<form [formGroup]="markerForm" (ngSubmit)="onSubmit(markerForm)" novalidate>
      <div class="form-group">
        <label for="markerType">{{ 'MARKER.LABEL_TYPE' | translate }}</label>
        <select  class="form-control" formControlName="markerType"   >
           <option id="markerType" [value]="markerType.id" *ngFor="let markerType of markerTypes">{{markerType.desc}}</option>
        </select>
      </div>
</form>
Run Code Online (Sandbox Code Playgroud)

设置默认值:

const test= [{id:1, desc: 'Restaurants'}, {id:2, desc : 'Fire stations'}];
this.markerTypes= test;
console.log(this.markerTypes[1].desc);
this.markerForm.controls['markerType'].setValue( this.markerTypes[1], {onlySelf: true});
Run Code Online (Sandbox Code Playgroud)

Ser*_*ell 5

出现问题是因为您将其markerType.id用作值,但将整个对象this.markerTypes[1]作为默认值发送。你应该通过this.markerTypes[1].id在这种情况下。

如果你想使用对象作为值,你应该ngValue在选项标签上使用指令:

<option id="markerType" [ngValue]="markerType" *ngFor="let markerType of markerTypes">{{markerType.desc}}</option>
Run Code Online (Sandbox Code Playgroud)

这是因为与值绑定不同,ngValue 支持绑定到对象

请参阅此处的工作示例