onselected event in md-select in Angular 4
Solution 1:
For Material version >= 6
Use the (selectionChange)
event on mat-select
.
<mat-form-field>
<mat-select placeholder="State" (selectionChange)="someMethod($event.value)">
<mat-option *ngFor="let state of states" [value]="state.value">
{{ state.viewValue }}
</mat-option>
</mat-select>
</mat-form-field>
In the event method, $event.value
contains the currently selected [value]
. Reference to the official documentation.
@Output() selectionChange: EventEmitter< MatSelectChange >
Event emitted when the selected value has been changed by the user.
Here is a link to Stackblitz Demo.
For Material version < 6
Use the (change)
output event.
<md-select placeholder="State" (change)="someMethod()">
<md-option *ngFor="let state of states" [value]="state.value">
{{ state.viewValue }}
</md-option>
</md-select>
Another way is to use (onSelectionChange)
event on <md-option>
:
<md-select placeholder="State">
<md-option *ngFor="let state of states" [value]="state.code"
(onSelectionChange)="anotherMethod($event, state)">
{{ state.name }}
</md-option>
</md-select>
Link to Stackblitz Demo.
Solution 2:
Alternatively you can just use the (click)
event on mat-option
. The click event is also fired when an already selected option is selected again. (change)
or (selectionChange)
will not fire in such a case.