简体   繁体   English

Angular 材料 Select 默认值未被选中

[英]Angular Material Select default value is not getting selected

I have a select box in which i have binded the array of objects.我有一个 select 盒子,我在其中绑定了对象数组。 I want to set a default intial value to it ie the 0th position value, i have tried using [(value)] and [(ngModel)] but it doesnt work.我想为其设置一个默认初始值,即第 0 个 position 值,我尝试使用 [(value)] 和 [(ngModel)] 但它不起作用。 Am i missing something?我错过了什么吗?

HTMl - HTMl -

<mat-form-field>
      <mat-label>Select</mat-label>
      <mat-select (selectionChange)="onLifeChange($event)" [(value)]="lifeId">
        <mat-option *ngFor="let life of lifeData" [value]="life">{{life?.fxlifeid}}</mat-option>
      </mat-select>
    </mat-form-field>

TS - TS -

 getLives(): void {
    this.insuredService.getLives(caseId).subscribe(res => {
      this.lifeData = res;
      this.numberOfLife = this.lifeData.length;
      this.lifeId = this.lifeData[0].fxlifeid;
    })
  }

I am calling getLives on ngOnInit.我在 ngOnInit 上调用 getLives。

Create a FormControl object in your component.ts file在您的 component.ts 文件中创建一个 FormControl object

formCotrolName = new FormCotrol();

In component.html file assign this object to mat-select control在 component.html 文件中将此 object 分配给 mat-select 控件

[formCotrol]='formCotrolName'

Now in your component.ts file, we get get the value from that dropdown by using formCotrol.value property.现在在您的 component.ts 文件中,我们使用 formCotrol.value 属性从该下拉列表中获取值。 But this value property is read only.但是这个值属性是只读的。 To set value we need use setValue method要设置值,我们需要使用 setValue 方法

formControl.setValue(value);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM