How to get the value and the text in an Angular Material mat-select
Update : 2020 (Updated answer as per the new version of angular material)
The below old answer worked for the OP at the time question was asked. But I observed comments on the old answer and output event, change
of mat-select
has been deprecated in the new version of angular material. So, the correct answer is
Working Stackblitz
HTML:
<mat-form-field>
<mat-select (selectionChange)="selectedValue($event)">
<mat-option [value]="'GB'">Great Britain</mat-option>
<mat-option [value]="'US'">United States</mat-option>
<mat-option [value]="'CA'">Canada</mat-option>
</mat-select>
</mat-form-field>
selectionChange
will give us an object contains 2 propertiesvalue
&source
value
will hold selected option value and- To get the selected option text, you can simply call
triggerValue
onsource
like below
TS:
selectedValue(event: MatSelectChange) {
this.selectedData = {
value: event.value,
text: event.source.triggerValue
};
console.log(this.selectedData);
}
Old Answer
With normal change event, you can get the value like below
In the .html file
<mat-select placeholder="Transaction Type" (change)="selected($event)" formControlName="TransactionTypeID">
<mat-option *ngFor="let t of transactionTypes" [value]="t.TransactionTypeID">
{{t.TransactionType}}
</mat-option>
</mat-select>
In the .ts file
selected(event) {
let target = event.source.selected._element.nativeElement;
let selectedData = {
value: event.value,
text: target.innerText.trim()
};
console.log(selectedData);
}
To complete preceding answer one can use viewValue of MatOption. Also Angular 7 compiler wants to know if event.source.selected should be an array or a single object.
selected(event: MatSelectChange) {
const selectedData = {
text: (event.source.selected as MatOption).viewValue,
value: event.source.value
};
console.log(selectedData);
}