Search code examples
angularng-template

Pass a function as an argument in an ng-template Angular


I have 4 buttons where I want them to do different actions but they all look the same with different images. So I've created an ng-template to render them. My idea was to pass the function that each one was going to call as a parameter in the ng-template but I can't find a way to do it.

Here is my idea:

<ng-template #tempalte let-icon=icon let-action=action let-alt=alt>
  <div (click)="action()">
    <img src={{icon}} alt={{alt}}>
  </div>
</ng-template>

Is what I am trying to do even possible? Or it's my logic wrong and I am making a mistake?

Thanks a lot!


Solution

  • You can totally do that with providing a context.

    <ng-container *ngTemplateOutlet="tempalte;context:ctx"></ng-container>
    <ng-container *ngTemplateOutlet="tempalte;context:ctx2"></ng-container>
    
    
    <ng-template #tempalte let-icon="icon" let-action="action" let-alt="alt">
      <div (click)="action()">
        <img src={{icon}} alt={{alt}}>
        Button
      </div>
    </ng-template>
    
    export class AppComponent {
      ctx = { action: () => alert('button1') };
      ctx2 = { action: () => alert('button2') };
    

    Here's the stackblitz demo