Angular中父组件监听子组件mat-select的change事件未触发问题
解决父组件监听子组件mat-select的change事件不触发问题
我来帮你搞定这个问题!你当前写法里的问题很明确:你把(change)绑定在了div元素上,但div本身根本不会触发change事件,只有表单类元素(比如原生select或者Angular Material的mat-select)才会触发这类事件。
下面是具体的修复步骤,分两步来:
第一步:让子组件B暴露mat-select的选择事件
首先要在子组件app-custom-mat-select-search里,把内部mat-select的selectionChange事件传递给父组件。
- 先在子组件的TypeScript文件里导入
Output和EventEmitter,并定义一个自定义输出事件:
import { Component, Input, Output, EventEmitter } from '@angular/core'; // ... 其他组件代码 @Component({ // ... 组件元数据 }) export class CustomMatSelectSearchComponent { // ... 你的其他@Input属性 // 定义一个输出事件,用来传递mat-select的选择变化 @Output() selectionChange = new EventEmitter<any>(); }
- 然后在子组件的模板里,给
mat-select绑定selectionChange事件,把事件对象emit出去:
<mat-form-field [formGroup]="selectFormGroup"> <mat-select [formControlName]="selectFormControlName" [compareWith]="selectCompareWith" [placeholder]="selectPlaceholder" [multiple]="multiple" #select <!-- 把mat-select的selectionChange事件传递给父组件 --> (selectionChange)="selectionChange.emit($event)" > <mat-option> <ngx-mat-select-search [formControl]="filterCtrl" placeholderLabel="Rechercher..." noEntriesFoundLabel="'Aucun résultat'"> <fa-icon icon="times" class="icon" ngxMatSelectSearchClear ></fa-icon> </ngx-mat-select-search> </mat-option> <mat-option *ngFor="let data of filteredData | async" [value]="data" > {{selectDataAccessor(data)}} </mat-option> </mat-select> </mat-form-field>
第二步:父组件A直接监听子组件的自定义事件
现在你可以把父组件里那个没用的div和它上面的(change)事件去掉,直接在子组件标签上绑定我们刚才定义的(selectionChange)事件:
<ng-container *ngIf="row.editing"> <app-custom-mat-select-search [options]="typesServeur | sortBy:['ordre','libelle']" [selectFormGroup]="row.form" [selectFormControlName]="'types_serveur'" [selectCompareWith]="matSelectCompareWithId" [selectPlaceholder]="" [selectDataAccessor]="matSelectDataAccessorByLibelle" multiple <!-- 直接监听子组件暴露的selectionChange事件 --> (selectionChange)="doSomething($event)" > </app-custom-mat-select-search> </ng-container>
这样修改之后,当子组件里的mat-select选项发生变化时,父组件的doSomething方法就会被正确调用啦!
内容的提问来源于stack exchange,提问作者Mo Elkinani
相关产品推荐
相关产品推荐

