【问题标题】:TemplateRef and click eventTemplateRef 和点击事件
【发布时间】:2018-10-08 14:42:05
【问题描述】:

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

<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>

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

【问题讨论】:

    标签: angular angular5 ng-template


    【解决方案1】:

    改变

    {method: test(), element:element}
    

    {method: test, element:element}
    

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

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

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

    Stackblitz Demo

    【讨论】:

    • 它什么都不做,没有错误但没有消息,我能错过别的吗?
    • 检查控制台日志。它在按钮单击时打印test called
    • 谢谢!那是我的缺失点,在模板中添加 () 就可以了!
    • 仅添加如果“test”功能不像“console.log”那么简单并使用组件“this”将{method:test}更改为{method:test.bind(this)}
    猜你喜欢
    • 1970-01-01
    • 2012-09-07
    • 1970-01-01
    • 2015-12-05
    • 2012-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-17
    相关资源
    最近更新 更多