簡體   English   中英

Angular 2子組件接收祖先事件

[英]Angular 2 child component receive ancestor event

我有一個Angular組件,它依賴於根App組件上發生的單擊事件。 孩子位於<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();
  }
}

Plunker

更新: Eric剛剛在另一個答案中發布了以下內容:

“你可以使用listenGlobal來訪問文檔,正文等。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM