How to get Id of selected value in Mat-Select Option in Angular 5

AtmanSangeetha picture AtmanSangeetha · Feb 9, 2018 · Viewed 67.8k times · Source

How to get the id of selected option value in mat-select angular 5. Get only value of selected option in onchangeevent. but how can get id of selected option value.

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

Answer

Stack Underflow picture Stack Underflow · Jan 9, 2019

The question is specific to Angular 5 but for others coming here with a newer version of Angular, the (change) event won't work for mat-select.

In Angular 6 the (change) event has been changed to (selectionChange).

So it would be:

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

And in the component:

changeClient(value) {
    console.log(value);
}

From this answer and the documentation.