遵循以下示例:
如何使用/创建动态模板与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所说的;您的动态创建组件中不存在打印杂物。如果我们在动态创建的组件中声明函数,我们可以调用它:
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()属性中传递对其的引用。