1
votes

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

3 Answers

2
votes

Demo It fires with only in html element change by user not by backend data change. You can use Viewchild as a way to manuel call function

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

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

in 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>
0
votes

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

0
votes

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); });