Reputation: 54698
I've got a component made of a ng-container
, I would like to bind a click on it. (click)
doesn't do the job.
Is there another way to do it ?
Upvotes: 7
Views: 14362
Reputation: 21
Tested in NG v11, you can do something like this where you wish to insert the custom template:
<ul>
<li *ngFor="let item of listData; index as i">
<ng-container
[ngTemplateOutlet]="customTemplate"
[ngTemplateOutletContext]="{
$implicit: item,
idx: i,
onclick: this.clickHandlerMethodInComponent.bind(this)
}"
></ng-container>
</li>
</ul>
And then define the custom template like this:
<ng-template #customTemplate
let-item
let-index="idx"
let-onclick="onclick">
<a (click)="onclick(item)">
<p>{{item.description}}</p>
</a>
</ng-template>
The key is to use the ngTemplateOutletContext attribute and the binding of the click handler to the component.
Upvotes: 2
Reputation: 24414
the ng-container
will not render as an element so there is no way you can rise the click event
@Directive({
selector: '[appClickHandler]'
})
export class ClickHandlerDirective {
@HostListener('click', ['$event']) log(e){
console.log(e)
}
}
this will not rise any click event
<ng-container appClickHandler>
<div>
ng container with click
</div>
</ng-container>
but you can add the click handler to an element inside the ng-container
<ng-container >
<div appClickHandler>
ng container with click
</div>
</ng-container>
ng-container The Angular is a grouping element that doesn't interfere with styles or layout because Angular doesn't put it in the DOM.
Here's the conditional paragraph again, this time using .
<p>
I turned the corner
<ng-container *ngIf="hero">
and saw {{hero.name}}. I waved
</ng-container>
and continued on my way.
</p>
Upvotes: 1
Reputation: 54698
Actually, @HostListener('click', ['$event'])
in the code does the job.
Asking the question made me think of it.
Upvotes: 5