TemplateRef 和点击事件

cuc*_*uru 4 ng-template angular angular5

我有一个针对不同组件但有一些按钮的通用模板。因此,我创建一个通用组件并使用 ng-template 更改此按钮:

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

<ng-template #buttonTemplate let-element="element" let-method>
  <button (click)="method">
        element.name              
  </button>
</ng-template>
Run Code Online (Sandbox Code Playgroud)

在组件common.component.ts中:

export class ComponentCommonComponent {

   @Input() buttonTemplate: TemplateRef<any>;

   constructor() { }

   test() {
      console.log("test called");
   }
}
Run Code Online (Sandbox Code Playgroud)

并在html中:

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

我发现的问题是“test”一直被调用,而我只想在单击时调用它,我错过了什么?

Sun*_*ngh 7

改变

{method: test(), element:element}
Run Code Online (Sandbox Code Playgroud)

{method: test, element:element}
Run Code Online (Sandbox Code Playgroud)

您不想调用该方法,而只需要方法的引用。

同样在模板中,您应该使用let-method="method"并将其称为method()

<ng-template ... let-method="method">
  <button (click)="method()">
Run Code Online (Sandbox Code Playgroud)

Stackblitz 演示

  • 只添加如果“test”功能不像“console.log”那么容易,并使用组件“this”通过{method:test.bind(this)}更改{method:test} (3认同)