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 ?
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 ?
Actually, @HostListener('click', ['$event'])
in the code does the job.
Asking the question made me think of it.
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.
bind(this)
in this.clickHandlerMethodInComponent.bind(this)
is what did it for me. Interestingly, removing the first this
works for me in angular v13 in 2022: clickHandlerMethodInComponent.bind(this)
. Ty β
Prestissimo 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>
<my comp class="my-classes
></my-comp> β
Rupertruperta <ng-container > <div appClickHandler> ng container with click </div> </ng-container>
the same as: `<ng-container > <div (click)="method()"> ng container with click </div> </ng-container> β
Rapids © 2022 - 2024 β McMap. All rights reserved.