Angular 2 how to execute script tag from innerHTML

后端 未结 2 1178
悲哀的现实
悲哀的现实 2020-12-15 00:04

I have load the HTML page by http.get() method, and i add content this page to div tag.

getRequestToAssignPage (param: string) : an         


        
2条回答
  •  暖寄归人
    2020-12-15 00:38

    In your template, you can set up something like:

    In the corresponding component, you can load your HTML into your template, build up an array of script tags, and eval each one:

    @ViewChild('htmlContainer') container;
    
    ngOnInit() {
      this.http.get('html-file.html').subscribe((res: Response) => {
        this.trustedHTML = this.sanitizer.bypassSecurityTrustHtml(res.text());
    
        setTimeout(() => { //wait for DOM rendering
          let scripts = this.container.nativeElement.getElementsByTagName('script');
          for (let script of scripts){
            eval(script.text)
          }
        })
    
      });
    

    I hate that I have to resort to using setTimeout and eval for something so seemingly simple, but it works.

    ...but not for

提交回复
热议问题