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