Angular 2子组件接收祖先事件 [英] Angular 2 child component receive ancestor event

查看:78
本文介绍了Angular 2子组件接收祖先事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Angular组件,它依赖于根App组件上发生的click事件.这个孩子位于<app>组件内的随机位置,因此为什么我没有列出它.

I have an Angular component that depends on a click event that occurs on the root App component. The child is located in random places inside the <app> component, hence why I didn't list it.

@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事件?

How can I have the child component receive the rootClickEmitter event?

推荐答案

对于在外部单击",请尝试以下操作:

For "click outside", try this:

@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)刚刚在另一个答案中发布了以下内容:

Update: Eric just posted the following in another answer:

您可以使用listenGlobal来访问文档,正文等.

"You can use listenGlobal that will give you access to document, body, etc.

renderer.listenGlobal('document', 'click', () => {
  console.log('Document clicked');
});

这篇关于Angular 2子组件接收祖先事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆