角度2:动态模板(动态组件)内部的单击功能/方法 [英] Angular 2: functions/methods on click inside dynamic template (dynamic component)
问题描述
下面的示例:
我如何使用/创建动态模板以使用Angular 2.0编译动态组件?
我开发了自己的模板生成器,该模板生成器直接从变量获取HTML内容. 这里是: http://plnkr.co/edit/2Sv1vp?p=preview
I developed my own template generator, which gets the HTML content directly from a variable. Here it is: http://plnkr.co/edit/2Sv1vp?p=preview
现在,我的问题是...模板内容是否必须与组件交互,例如单击时执行的功能...我该怎么做?
Now, my question is... if template content has to interact with the component, for example with a function to execute on click... how can I do that?
这是我的app.component.ts
Here my 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 template"时,它应该执行printSomething()
函数,但我却收到此错误:
When I try click on "Sono il secondo template", it should execute printSomething()
function, but instead I obtain this error:
Error in ./CustomDynamicComponent class CustomDynamicComponent - inline template:0:0 caused by: self.context.printSomething is not a function
推荐答案
问题出在Angular所说的那样.动态创建的组件中不存在printSomething.如果我们在动态创建的组件中声明一个函数,则可以调用它:
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;
}
如果要在app.component.ts中调用方法,则需要在CustomDynamicComponent的新@Input()属性中传递对该方法的引用.
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.
这篇关于角度2:动态模板(动态组件)内部的单击功能/方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!