6

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 ?

Matthieu Riegler
  • 31,918
  • 20
  • 95
  • 134
  • 5
    You can't because ng-container doesn't get rendered in the html template. So, since the code wont be transpiled in the actual DOM, that element will not exists at runtime. – Jacopo Sciampi Nov 22 '19 at 10:59

3 Answers3

4

Actually, @HostListener('click', ['$event']) in the code does the job.

Asking the question made me think of it.

Matthieu Riegler
  • 31,918
  • 20
  • 95
  • 134
1

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>

demo

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>

ng-continer doc

Muhammed Albarmavi
  • 23,240
  • 8
  • 66
  • 91
1

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.

  • The call to `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 – wraiford Nov 16 '22 at 15:29