简体   繁体   中英

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.

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 SOLID).

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM