在mat-select-Angular Material中,默认选项不会发出selectionChange

时间:2018-12-27 14:05:41

标签: angular angular-material

我想在使用默认值初始化mat-select时触发回调(或发出事件)。请参见下面的模板-

<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>

onSelectionChange($event)初始化时是否可以调用mat-select

1 个答案:

答案 0 :(得分:1)

您可以尝试添加模板引用(此处:#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>

然后在Ts部分中,假设您按如下所示填充该默认值:

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

您可以像这样继续使用AfterViewInitViewChild

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.(您将拥有Error: Object too large to inspect. Open your browser console to view.,因此,请打开浏览器控制台:))