[英]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. 我想在使用默认值初始化
mat-select
时触发回调(或发出事件)。 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? 初始化
mat-select
时,有没有办法调用onSelectionChange($event)
?
You can try adding a template ref (here : #select
): 您可以尝试添加模板引用(此处:
#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: 然后在您的Ts部分中,假设您按如下所示填充该默认值:
constructor() {
this.selectedSearchView = this.searchViews[0]
}
You can proceed using AfterViewInit
and ViewChild
like this: 您可以像这样继续使用
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. 工作演示。 (You'll have
Error: Object too large to inspect. Open your browser console to view.
so , open your browser console :) ) (您将看到
Error: Object too large to inspect. Open your browser console to view.
因此,请打开浏览器控制台:))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.