在Angular 2中捕获有关ng-content的事件 [英] Capture event on ng-content in Angular 2
问题描述
我正在通过本教程来理解角度2. ng-content
.我想捕获在 ng-content
上触发的事件.我有以下组件:
I am going through this tutorial to comprehend angular 2's ng-content
. I want to capture event which is triggered on ng-content
. I have following component:
@Component({
moduleId: module.id,
selector: 'card',
template: `
<ng-content (click)="onClick($event)"></ng-content>
`
})
export class CardComponent {
onClick(){
console.log('clicked');
}
}
在这里,如您所见,我正在为 click
事件设置一个侦听器.但是由于某些原因,它并没有触发.似乎整个 ng-content
标签已被替换.因此,要捕获当前的事件,我正在这样做:
Here, as you can see I am setting a listener to the click
event. But for some reasons it is not triggering. It seems like the entire ng-content
tag is replaced. So to capture the event currently I am doing this:
template: `
<div (click)="onClick($event)">
<ng-content></ng-content>
</div>
`
有没有更好的方法可以做到这一点?因为我不想将我的 ng-content
包装到 div
中以避免样式问题.谢谢. Plnkr
Is there any better way to do this? cause I don't want to wrap my ng-content
into a div
to avoid styling issues. Thanks. Plnkr
推荐答案
通过使用主机声明将事件侦听器绑定到组件元素,您可以实现几乎相同的结果.
You can achieve pretty the same result by binding event listeners to the component element with host declaration.
import { Component, HostListener } from '@angular/core';
@Component({
selector: 'card',
template: `<ng-content></ng-content>`
})
export class ButtonComponent {
@HostListener('click', ['$event.target'])
onClick(target) {
console.log('Clicked on: ', target);
}
}
这篇关于在Angular 2中捕获有关ng-content的事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!