繁体   English   中英

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

[英]selectionChange does not emit for default option in mat-select - 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>

初始化mat-select时,有没有办法调用onSelectionChange($event)

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

}

工作演示。 (您将看到Error: Object too large to inspect. Open your browser console to view.因此,请打开浏览器控制台:))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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