Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TemplateRef and click event

I have a common template for different components but some buttons. So, I create a common component and change this buttons with ng-template:

<component-common 
       [buttonTemplate]="buttonTemplate">
</component-common>

<ng-template #buttonTemplate let-element="element" let-method>
  <button (click)="method">
        element.name              
  </button>
</ng-template>

In component-common.component.ts:

export class ComponentCommonComponent {

   @Input() buttonTemplate: TemplateRef<any>;

   constructor() { }

   test() {
      console.log("test called");
   }
}

and in html:

<ng-template 
    *ngTemplateOutlet="buttonTemplate;context: {method: test(), element:element}">
</ng-template>

The proble I found is "test" is called all the time, and I just want it to be called when clicking, what are I'm missing?

like image 700
cucuru Avatar asked Oct 31 '25 02:10

cucuru


1 Answers

Change

{method: test(), element:element}

To

{method: test, element:element}

You don't want to call the method instead you just need a reference of method.

Also in template you should be using let-method="method" and call it as method():

<ng-template ... let-method="method">
  <button (click)="method()">

Stackblitz Demo

like image 111
Sunil Singh Avatar answered Nov 02 '25 15:11

Sunil Singh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!