如何在Angular 5中的Mat-Select选项中获取所选值的Id

Atm*_*tha 11 angular angular-material-5

如何在mat-select angular中获取所选选项值的id 5.仅获取onchangeevent中所选选项的值.但是如何获得所选选项值的id.

 client.component.html
<mat-form-field>
    <mat-select placeholder="Client*" #clientValue  (change)="changeClient($event)">
    <mat-option  *ngFor="let client of clientDetails"   [value]="client.clientName">
      {{client.clientName |  json}}
    </mat-option>
  </mat-select>
</mat-form-field>

client.component.ts file
export class Client{
     changeClient(event){
     console.log(event);
 }
}
Run Code Online (Sandbox Code Playgroud)

Viv*_*shi 23

为此你需要:

更改(change)="changeClient($event)"(change)="changeClient($event.value)"

从... [value]="client.clientName"[value]="client.id"

<mat-form-field>
    <mat-select placeholder="Client*" #clientValue  (change)="changeClient($event.value)">
    <mat-option  *ngFor="let client of clientDetails"   [value]="client.id">
      {{client.clientName}}
    </mat-option>
  </mat-select>
</mat-form-field>
Run Code Online (Sandbox Code Playgroud)

工作演示


Sta*_*low 16

这个问题是针对Angular 5的,但是对于其他使用较新版本Angular的用户而言,该(change)事件不适用于垫选。

Angular 6中(change)事件已更改为(selectionChange)

因此它将是:

<mat-form-field>
    <mat-select placeholder="Client*" #clientValue  (selectionChange)="changeClient($event.value)">
    <mat-option  *ngFor="let client of clientDetails" [value]="client.id">
      {{client.clientName}}
    </mat-option>
  </mat-select>
</mat-form-field>
Run Code Online (Sandbox Code Playgroud)

并在组件中:

changeClient(value) {
    console.log(value);
}
Run Code Online (Sandbox Code Playgroud)

这个答案文档

  • 这次真是万分感谢。我已经搜索了一个小时。 (3认同)