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);
}
}
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:
And in the component:
From this answer and the documentation.
For that you need to :
Change
(change)="changeClient($event)"
to(change)="changeClient($event.value)"
and from
[value]="client.clientName"
to[value]="client.id"
WORKING DEMO
WORKING DEMO
You can also subscribe to the values change of the
mat-select
by using theViewChild
decorator andngAfterViewInit
which is less 'html-intrusive'.Here is an example :
[HTML]
[TS]
With this your value should be logged in the development console
Ctrl+Shift+I
orF12
everytime you change your selector value.or you can literally just do this if you dont need onchange :
[HTML]