Event not working in dynamic html in angular2

放肆的年华 提交于 2019-12-12 03:58:21

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/44786555/event-not-working-in-dynamic-html-in-angular2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!