Angular中子组件触发父组件中的事件的两种方式
方式一(不推荐,容易产生循环依赖):
- 在子组件的TS文件中 import 引入父组件,并在 constructor 注册。
- 通过this.子组件别名.方法名(),即可调用
// 步骤1
import { ExternalPersonManageComponent } from '../external-person-manage.component';
export class PerAddEditComponent implements OnInit {
// 步骤2
constructor(private externalPersonManageComponent: ExternalPersonManageComponent) {}
do() {
// 步骤3
this.externalPersonManageComponent.getListByComId()
}
}
方式二(推荐):
- 通过emit自定义事件触发父组件的方法
// 子组件TS文件:
// 步骤1
import { Output,EventEmitter } from '@angular/core';
export class PerAddEditComponent implements OnInit {
constructor() {}
// 步骤2
@Output() refresh: EventEmitter<any> = new EventEmitter<any>();
// 步骤3
do() {
this.refresh.emit('');
}
}
// 父组件HTML:
<子组件 (refresh)="父组件的方法()"></子组件>
本文来自博客园,作者:RHCHIK,转载请注明原文链接:https://www.cnblogs.com/suihung/p/16458703.html