Sikander Sikander - 5 months ago 33
TypeScript Question

Event not working in dynamic html in angular2

Want to append the dynamic generated html in a DOM, its appending successfully in a DOM but none of the function is working like click etc.

ngOnInit() {
this.sideBarData += '<li class="sidebar-toggler-wrapper hide" >' +
'<div class="sidebar-toggler" > </div>' +
'</li>' +
'<li class="sidebar-search-wrapper"></li>';
this.sideBarData += '<li class="nav-item start">' +
'<a class="nav-link home name" (click)="HomeButton(event)">' +
'<i class="fa fa-home"></i>' +
'<span class="title">Home</span>' +
'</a>' +
'</li>';
this.getJSONService.getData()
.subscribe(response => {
var value=response.datas
if (value.length > 0) {
for (var i = 0; i < value.length; i++) {
if (value[i].state)
{
this.sideBarData += '<li class="nav-item" >' +
'<a (click)="parentNav($event)" routerLink="/' + value[i].state + '" class="nav-link nav-toggle ' + value[i].key + '" >' +
'<i class="fa fa-' + value[i].label_Icon + '"></i>' +
'<span class="title">' + value[i].label + '</span>';
if (this.checkDataExist(value[i]))
{
var data1 = this.data(value[i]);
}
this.sideBarData += '</a></li>';
} else
{
this.sideBarData += '<li class="nav-item" >' +
'<a class="nav-link nav-toggle ' + value[i].key + '" (click)="parentNav($event)">' +
'<i class="fa fa-' + value[i].label_Icon + '"></i>' +
'<span class="title">' + value[i].label + '</span>';
if (this.checkDataExist(value[i]))
{
var data1 = this.data(value[i].data);
}
this.sideBarData += '</a></li>';
this.sidebarChild.element.nativeElement.innerHTML=this.sideBarData
}
}
}
})
}


Data is appending in DOM but no any event call is working..

Can you please help.
Thanks in advance.

Answer Source

Setting html in DOM directly by yourself isn't the right way of doing things in Angular. The right way is to split your code into Components, where each Component should have it's own responsibilaty (S in S.O.L.I.D.).

And for this kind of interactivaty (showing/hiding, styling) you should use: ngIf, ngSwitch, ngClass in your templates.