Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capture event on ng-content in Angular 2

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

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>
    `

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

like image 628
Hitesh Kumar Avatar asked Mar 02 '17 11:03

Hitesh Kumar


2 Answers

You can use @ContentChild to capture the events of projected component.

Child:

@Component({
moduleId: module.id,
selector: 'card-child',
template: `
<div>Card Child component</div>
`
})
export class CardChildComponent {
     @Output customEvent:EventEmitter = new EventEmitter()
}

Parent:

@Component({
moduleId: module.id,
selector: 'card',
template: `
<ng-content></ng-content>
`
})
export class CardComponent {
    @ContentChild(CardChildComponent) childComp: CardChildComponent;

    ngAfterContentInit() {
        this.childComp.addEventListener("click", ()=>{console.log("clicked"});
        //Below is handling of custom event
        this.childComp.customEvent.subscribe(()=>{console.log("clicked"});
    }
}

Below is how the component will be injected.

<card>
<card-child></card-child>
</card>
like image 112
Emmad Zahid Avatar answered Sep 27 '22 16:09

Emmad Zahid


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

}
like image 25
Dzmitry Vasilevsky Avatar answered Sep 27 '22 16:09

Dzmitry Vasilevsky