Need to insert Script tag in angular 2

前端 未结 5 1108
被撕碎了的回忆
被撕碎了的回忆 2020-11-27 18:22

I\'ve already done a bit of reading and searching and pretty much everything I find points to that a script tag cannot be included in a template in Angular 2.

5条回答
  •  难免孤独
    2020-11-27 18:24

    Having scripts in your views is usually a bad practice. If you insist on doing this you can use this component:

    scripthack.component.html:

    scripthack.component.ts:

    import { Component, ElementRef, ViewChild, Input } from '@angular/core';
    
    @Component({
        selector: 'script-hack',
        templateUrl: './scripthack.component.html'
    })
    export class ScriptHackComponent {
    
        @Input()
        src: string;
    
        @Input()
        type: string;
    
        @ViewChild('script') script: ElementRef;
    
        convertToScript() {
            var element = this.script.nativeElement;
            var script = document.createElement("script");
            script.type = this.type ? this.type : "text/javascript";
            if (this.src) {
                script.src = this.src;
            }
            if (element.innerHTML) {
                script.innerHTML = element.innerHTML;
            }
            var parent = element.parentElement;
            parent.parentElement.replaceChild(script, parent);
        }
    
        ngAfterViewInit() {
            this.convertToScript();
        }
    }
    

    usage (inline):

    alert('hoi');
    

    usage (external):

    
    

提交回复
热议问题