Here is an example to demonstrate how to create dynamic templates and compile dynamic components in Angular 2.0:
How can I use/create dynamic template to compile dynamic Component with Angular 2.0?
I have built my own template generator that fetches HTML content directly from a variable. You can find the generator here: http://plnkr.co/edit/2Sv1vp?p=preview
My question now is, how can I make the template content interact with the component, such as executing a function on click event?
Below is my app.component.ts code:
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",
name: "Bea"
};
this.tmpl1 = '<h2>I am {{entity.name}}, the first template</h2>';
this.tmpl2 = '<a (click)="printSomething()">I am the second template</a>';
}
printSomething() {
console.log("Hello World");
}
}
When I try to click on "I am the second template", it should execute the printSomething()
function, but instead I get this error:
Error in ./CustomDynamicComponent class CustomDynamicComponent - inline template:0:0 caused by: self.context.printSomething is not a function