Angular Material Select, selectionChange not firing

Viewed 6109

I have prepared example (Angular Material Select):

Stackblitz

I have set value on ngOnInIt for mat-select, but selectionChange event is not firing. Whenever I set value to mat-select with value property, I want that selectionChange is fired, and I want to do some work on selectionChange.

selectionChange is firing on manual user selection, but not on setting value.

Why selectionChange event is not firing?

Is there any other event or approach to achieve this ?

3 Answers

Demo The selectionChange event fires only when the html element is changed by a user and not by backend data change. You can use Viewchild as a way to manually call a function:

@ViewChild("changeEl") el!: ElementRef;

    ngAfterViewInit(){
        this.selectedFood = this.foods[0].value;
        this.selectionChangeTax(this.el)
      }

HTML:

<h4>Basic mat-select</h4>
<mat-form-field appearance="fill">
  <mat-label>Favorite food</mat-label>
  <mat-select (selectionChange)="selectionChangeTax($event)" #changeEl [(value)]="selectedFood">
    <mat-option *ngFor="let food of foods" [value]="food.value">
      {{food.viewValue}}
    </mat-option>
  </mat-select>
</mat-form-field>

You can use valueChange if you want to know about all the changes.

on ngOnInit

this.myForm = this.formBuilder.group({ firstName: [this.firstName], lastName: [this.lastName] });

 this.myForm.controls['firstName'].valueChanges.subscribe(value => { console.log(value); });

This is expected behavior. However I have prepared StackBlitz where I use RxJS to subscribe to new value in the select. Whenever the values gets changed, next callback in the subscription will be fired. See console for output.

https://stackblitz.com/edit/angular-bhwtam-udkedb

Related