我有一个 Angular 组件,它依赖于发生在根 App 组件上的点击事件。 child 位于 <app>
内的随机位置组件,因此我没有列出它。
@Component({
template: '<div>Child!</div>'
})
export class Child {
constructor () {}
}
@Component({
selector: 'app',
template: '<div (click)=foo()></div>'
})
export class App {
rootClickEmitter = new EventEmitter();
foo () {
this.rootClickEmitter.emit('bar');
}
}
我怎样才能让子组件接收到 rootClickEmitter
事件?
最佳答案
对于“点击外部”,试试这个:
@Component({
selector: 'child',
template: '<div (click)="childClick($event)">child content here</div>',
host: { '(document:click)': 'docClick()' }
})
export class Child {
docClick() {
console.log('clicked outside');
}
childClick(ev) {
console.log('child click');
ev.stopPropagation();
}
}
更新: Eric 刚刚在 another answer 中发布了以下内容:
“您可以使用 listenGlobal 来访问文档、正文等。
renderer.listenGlobal('document', 'click', () => {
console.log('Document clicked');
});
关于javascript - Angular 2子组件接收祖先事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35028267/