Issue
I am trying to attach onSelectionChange
event on select
as follows:
<mat-form-field class="full-width languageDiv" appearance="outline" *ngIf="languages && selectedLanguage">
<mat-label>Language</mat-label>
<mat-select [(value)]="selectedLanguage">
<mat-option *ngFor="let language of languages" [value]="language" (onSelectionChange)="onLangChange($event)">
{{language}}
</mat-option>
</mat-select>
</mat-form-field>
Here is the onLangChange
method
onLangChange(e) {
console.log(e);
const languageSelected = e.source.value;
if( this.selectedLanguage !== languageSelected){
this.selectedLanguage = (languageSelected);
}
}
Here is the stackblitz
link:
StackBlitz
For every change in selection, onLangChange
is getting called twice which is messing up my other logic (not mentioned here to keep the code simple). Why is this getting called twice?
Solution
You should use ngModel with ngModelChange as follows, The reason being is that you are using onSelectionChange on mat-option, while it should be on the mat-select. It is always better to go with ngModelChange as shown below,
<mat-select [(ngModel)]="selectedLanguage" (ngModelChange)="onLangChange($event)">
<mat-option *ngFor="let language of languages" [value]="language">
{{language}}
</mat-option>
</mat-select>
Answered By - Sajeetharan
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.