i have to load Html data from server like i have 'click'
but when i assign this data to innerHtml property in angular2 it shows html but click even is not working .
is there any solution for this problem.
there are some suggestions to use dynamic Components but i don't find any good tutorial for final angular2 release.
import { Component, ViewChild, ElementRef, OnInit, Directive } from '@angular/core';
import { HttpComponent} from './http.component';
import {DomSanitizer, SafeHtml} from '@angular/platform-browser';
@Component({
moduleId: module.id,
selector: 'my-app',
template: `<div [innerHTML]="myVal"></div>`
})
export class AppComponent {
myVal: string = '<div><button onClick="showdata()"> Show Data </button></div>';
constructor(){}
showdata(){
console.log("test");
}
}
If you assign a click handler this way, it won't refer to the
showdata()
in Angulars component but forwindow.showdata()
. Angular doesn't know aboutonclick
andonclick
doesn't know about Angular.I would suggest you add the HTML to the component, then query for the element and add an event handler using
While
ngAfterViewInit()
might not be the right place for the code, depending on when the HTML is added.My proposal is to use JavaScript to listen the click event and get the element by id:
component:
template:
Its working for me.