Capturing events on ng content in Angular 2

I am going through this tutorial to understand angular 2 ng-content. I want to capture an event that fires on ng-content. I have the 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 set the listener to the event click. But for some reason this does not work. It seems that the whole tag is ng-contentreplaced. Therefore, to capture this event, I do this:

template: `
    <div (click)="onClick($event)">
      <ng-content></ng-content>
    </div>
    `

Is there a better way to do this? because I donโ€™t want to wrap my ng-contentin divto avoid design problems. Thank you Plnkr

+6
source share
1 answer

<ng-content> , . Angular .

DIV - ng-content.

, , <ng-content>. AppContentComponent (-),

<app-content (click)="onClick()">
   <ng-content></ng-content>
</app-content>

, , ( <div>, <app-content>), , , <ng-content>, , , .

0

Source: https://habr.com/ru/post/1015401/


All Articles