我想在使用默认值初始化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
?
答案 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]
}
您可以像这样继续使用AfterViewInit
和ViewChild
:
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.
,因此,请打开浏览器控制台:))