在 Angular 文档中有一个关于监听来自 parent 的 child 事件的话题。没关系。但我的目的是相反的!在我的应用程序中有一个“admin.component”,它包含管理页面的布局 View (侧边栏菜单、任务栏、状态等)。 在这个父组件中,我配置了路由器系统,用于在管理员的其他页面之间更改主视图。 问题在于更改后保存内容,用户单击任务栏中的保存按钮(位于 admin.component 中),子组件必须监听该单击事件以保存人员。
最佳答案
为了后代,我想我会提到更传统的解决方案:简单地获取对 ViewChild 的引用,然后直接调用它的方法之一。
@Component({
selector: 'app-child'
})
export class ChildComponent {
notifyMe() {
console.log('Event Fired');
}
}
@Component({
selector: 'app-parent',
template: `<app-child #child></app-child>`
})
export class ParentComponent {
@ViewChild('child')
private child: ChildComponent;
ngOnInit() {
this.child.notifyMe();
}
}
关于javascript - child 在 Angular 2 中监听父事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37677122/