Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onselected event in md-select in Angular 4

I would like call a function in typescript on choosing a value using md-select. What is the property used for this purpose in material design ?

   <md-select placeholder="State">        <md-option *ngFor="let state of states" [value]="state.code">{{ state.name }}    </md-option> 

like image 617
Karthik Kumar Avatar asked Sep 04 '17 11:09

Karthik Kumar


People also ask

How to use md select in Angularjs?

Selectable options are defined using the md-option element directive. Options can be grouped using the md-optgroup element directive. When the select is required and uses a floating label, then the label will automatically contain an asterisk ( * ). This behavior can be disabled by using the md-no-asterisk attribute.

How do you focus a mat select?

Try using MatSelect on viewChild to access focused attribute, then onInit set it to true. This in incorrect AFAIK. It sets the style to focused but this not actually focuses the element!

What is a mat select trigger?

MatSelectTrigger. Allows the user to customize the trigger that is displayed when the select has a value.


1 Answers

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.

like image 165
Faisal Avatar answered Oct 10 '22 06:10

Faisal