Dynamically displaying elements containing HTML with (click) functions Angular 2
angular, typescript2.0
Solution
CFR DEMO : https://plnkr.co/edit/jKEaDz1JVFoAw0YfOXEU?p=preview
@Component({
selector: 'my-app',
template: `
<button (click)="addComponents()">Add HTML (dynamically using CRF)</button>
<h1>Angular2 AppComponent</h1>
<hr>
<div>
<h5>dynamic html goes here</h5>
<div class="container">
<template #subContainer1></template>
</div>
</div>
`,
})
export class App {
name:string;
@ViewChild('subContainer1', {read: ViewContainerRef}) subContainer1: ViewContainerRef;
constructor(
private compFactoryResolver: ComponentFactoryResolver
) {
this.name = 'Angular2'
}
addComponents() {
let compFactory: ComponentFactory;
compFactory = this.compFactoryResolver.resolveComponentFactory(Part1Component);
this.subContainer1.createComponent(compFactory);
}
}
Problem
I have a recursive tree structure containing nodes which each have an 'htmlStringContent' property. When I display the tree using nested 'node' components and try to present the html content I use: ``` <div [innerHtml]="node.htmlStringContent"></div> ``` The HTML displays correctly but for the following elements: ``` <a (click)="function()">click me</a> ``` The (click) functions don't work. I know this has previously been posted but with the large amount of updates angular has brought out recently I cant find any solutions. This answer leads me to believe I should be using the ngComponentOutlet directive but I'm not sure how.. How can I get angular to bind this click functionality? Edit: I have been told to use the ComponentFactoryResolver but can't see how I can use this to display the html correctly. Can anyone provide further help? Edit2: I am parsing 'htmlStringContent' through a sanitizing pipe before displaying it on [innerHtml] ``` transform(v: string) : SafeHtml { return this._sanitizer.bypassSecurityTrustHtml(v); } ``` Edit3: Basically this question is asking whether it is as all possible to display HTML from a property on an object in angular 2/ionic 2 while retaining the (click) functionality on it. I am also open to workaround answers.