Angular 2: functions/methods on click inside dynamic template (dynamic component)

跟風遠走 提交于 2019-11-29 12:57:32

The problem is as Angular says; printSomething does not exist in your dynamically created component. If we declare a function within the dynamically created component, we are able to call it:

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

If you want to call a method in app.component.ts, you'll need to pass a reference to it in a new @Input() attribute of CustomDynamicComponent.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!