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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With