Angular 响应式表单 Select 默认对象

Angular Reactive forms Select default object

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

我的表格:

<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>

设置默认值:

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});

试试这个

检查这个https://stackblitz.com/edit/angular-rqhchz?embed=1

Component.html

<form [formGroup]="markerForm">
   <select id="country" formControlName="markerType">
       <option *ngFor="let c of markerTypes" [ngValue]="c.id">{{ c.desc }} 
      </option>
   </select>
</form>

component.ts

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

export class Component {

   markerTypes = [{id:1,desc:'abc'}, {id: 2,desc:'xyz'}];
   default= 1;

   markerForm: FormGroup;

   constructor() {
       this.markerForm= new FormGroup({
           markerType: new FormControl(null)
       });
     this.markerForm.controls['markerType'].setValue(this.default, {onlySelf: true});
    }
}

希望这会有所帮助

问题的发生是因为您使用 markerType.id 作为值,但默认发送整个对象 this.markerTypes[1]。在这种情况下,您应该传递 this.markerTypes[1].id

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

<option id="markerType" [ngValue]="markerType" *ngFor="let markerType of markerTypes">{{markerType.desc}}</option>

这是因为unlike the value binding, ngValue supports binding to objects

查看工作示例here

您正在将默认值设置为对象:

this.markerForm.controls['markerType'].setValue( this.markerTypes[1], {onlySelf: true});

你说你的值是一个 id:

 <option id="markerType" [value]="markerType.id" *ngFor="let markerType of markerTypes">{{markerType.desc}}</option>

这里有多种选择,这取决于您希望表单值如何。

使用 ID:

this.markerForm.controls['markerType'].setValue( this.markerTypes[1].id, {onlySelf: true});

<option id="markerType" [value]="markerType.id" *ngFor="let markerType of markerTypes">{{markerType.desc}}</option>

使用说明:

this.markerForm.controls['markerType'].setValue( this.markerTypes[1].desc, {onlySelf: true});

<option id="markerType" [value]="markerType.desc" *ngFor="let markerType of markerTypes">{{markerType.desc}}</option>

使用对象:

在这种情况下,您必须使用 [ngValue],[value] 仅用于类型字符串变量。

this.markerForm.controls['markerType'].setValue( this.markerTypes[1], {onlySelf: true});

<option id="markerType" [value]="markerType" *ngFor="let markerType of markerTypes">{{markerType.desc}}</option>

Working Example