简体   繁体   中英

selectionChange does not emit for default option in mat-select - Angular Material

I want to trigger a callback (or emit event) when mat-select is initialised with default value. Please see below template -

<mat-form-field>
          <mat-select [(value)]="selectedSearchView"  (selectionChange)="onSelectionChange($event)" >
            <mat-option *ngFor="let view of searchViews; let i=index" [value]="view">
              {{view.name}}
            </mat-option>
          </mat-select>
</mat-form-field>

Is there a way to call onSelectionChange($event) when mat-select is initialised?

You can try adding a template ref (here : #select ):

<mat-form-field>
          <mat-select #select [(value)]="selectedSearchView"  (selectionChange)="onSelectionChange($event)" >
            <mat-option *ngFor="let view of searchViews; let i=index" [value]="view">
              {{view.name}}
            </mat-option>
          </mat-select>
</mat-form-field>

Then in your Ts part, assuming you fill that default value as following:

constructor() {
    this.selectedSearchView = this.searchViews[0]
  }

You can proceed using AfterViewInit and ViewChild like this:

export class MyComponent implements AfterViewInit {

  selectedSearchView;
  searchViews = [
  {'name':'abc'},
  {'name':'def'},
  {'name':'ghi'}];

  @ViewChild('select') select;

  constructor() {
    this.selectedSearchView = this.searchViews[0]
  }

  onSelectionChange(event) {
    console.log('onSelectionChange called ! passed event :', event);
  }

  ngAfterViewInit() {
    if (this.select.value) {
      // here you can pass whatever you want as a parameter , I made an event-like object
      this.onSelectionChange({source:this.select, value: this.select.value});
    }
  }

}

Working demo. (You'll have Error: Object too large to inspect. Open your browser console to view. so , open your browser console :) )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM