角2子组件收到祖先事件 [英] Angular 2 child component recieve ancestor event

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

问题描述

我有依赖于根应用程序组件上发生了点击事件的角度成分。孩子坐落在里面随意的地方<应用方式> 组件,因此为什么我没有列出它

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

推荐答案

有关点击之外,试试这个:

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();
  }
}

<大骨节病> Plunker

更新:埃里克只是张贴在另一个答案:

你可以用listenGlobal,会给你访问记录,身体等。

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

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

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

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