渲染后如何在模板中执行任何javascript? Angular 2

时间:2017-02-22 13:12:11

标签: javascript angular templates

我有一个页面,我尝试使用脚本插入HTML。

import {
    Component,
    AfterViewInit,
    ViewChild,
    ElementRef
} from '@angular/core';
@Component({
    selector: 'menu-blocks-menupage',
    template: `<div class="menuArticle" #dataContainer (click)="logit()" padding></div>`
})
export class MenuBlocksMenuPage implements AfterViewInit {
    menu: MenuItem;
    //Контейнер для вставки
    @ViewChild('dataContainer') dataContainer: ElementRef;
    ngAfterViewInit() {
        this.dataContainer.nativeElement.innerHTML = "<script type='text/javascript'>" + "alert('123123213');" + "</script>";
    }
}

在渲染后插入带脚本标记的HTML,但没有任何反应。有什么问题?

答案:

ngAfterViewInit()
      {
        const fragment = document.createRange().createContextualFragment("<script type='text/javascript'>" +
  "alert('123123213');" +
  "</script>");
        this.dataContainer.nativeElement.appendChild(fragment);
      }

0 个答案:

没有答案