代码之家  ›  专栏  ›  技术社区  ›  cucuru

TemplateRef和click事件

  •  0
  • cucuru  · 技术社区  · 6 年前

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

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

    在component-common.component.ts中:

    export class ComponentCommonComponent {
    
       @Input() buttonTemplate: TemplateRef<any>;
    
       constructor() { }
    
       test() {
          console.log("test called");
       }
    }
    

    在html中:

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

    1 回复  |  直到 6 年前
        1
  •  3
  •   yurzui    6 年前

    改变

    {method: test(), element:element}
    

    {method: test, element:element}
    

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

    也在模板中,你应该使用 let-method="method" method() :

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

    Stackblitz Demo