【问题标题】:Angular 2: functions/methods on click inside dynamic template (dynamic component)Angular 2:点击动态模板(动态组件)内的函数/方法
【发布时间】:2017-04-30 02:37:46
【问题描述】:

按照下面的例子:

How can I use/create dynamic template to compile dynamic Component with Angular 2.0?

我开发了自己的模板生成器,它直接从变量中获取 HTML 内容。 这里是: http://plnkr.co/edit/2Sv1vp?p=preview

现在,我的问题是……如果模板内容必须与组件交互,例如与单击时执行的函数……我该怎么做?

这里是我的 app.component.ts

import { Component }          from '@angular/core';

@Component({
  selector: 'my-app',  
  template: `
    <div>
      <h2>An app with DYNAMIC content</h2>
      <hr />
      <dynamic-detail [tmpl]="tmpl1" [entity]="entity"></dynamic-detail>
      <dynamic-detail [tmpl]="tmpl2" [entity]="entity"></dynamic-detail>
    </div>`,
   })
   export class AppComponent { 
     private tmpl: string;
     private entity: any;

     constructor() {
       this.entity = { 
         code: "ABC123",
         description: "A description of this Entity",
         nome: "Bea"
       };

       this.tmpl1 = '<h2>Sono {{entity.nome}}, il primo template</h2>';
       this.tmpl2 = '<a (click)="printSomething()">Sono il secondo template</a>';
      }

    printSomething() {
      console.log("Hello World");
    }
}

当我尝试点击“Sono il secondo 模板”时,它应该执行printSomething() 函数,但我得到了这个错误:

 Error in ./CustomDynamicComponent class CustomDynamicComponent - inline template:0:0 caused by: self.context.printSomething is not a function

【问题讨论】:

    标签: angular typescript compilation angular2-compiler


    【解决方案1】:

    问题正如 Angular 所说的那样; printSomething 在您动态创建的组件中不存在。如果我们在动态创建的组件中声明一个函数,我们就可以调用它:

    app.component.ts

    this.tmpl2 = '<a (click)="linkClicked()">Sono il secondo template</a>';
    

    type.builder.ts

      protected createNewComponent(tmpl: string) {
        @Component({
          selector: 'dynamic-component',
          template: tmpl,
        })
        class CustomDynamicComponent implements IHaveDynamicData {
          @Input() public entity: any;
    
          linkClicked() {
            console.log('yay!');
          }
    
        };
        // a component for this particular template
        return CustomDynamicComponent;
      }
    

    如果您想调用 app.component.ts 中的方法,您需要在 CustomDynamicComponent 的新 @Input() 属性中传递对它的引用。

    【讨论】:

      猜你喜欢
      • 2017-04-05
      • 2017-10-18
      • 1970-01-01
      • 2017-05-03
      • 2018-02-02
      • 2016-11-11
      • 2018-01-04
      • 2015-10-19
      相关资源
      最近更新 更多