2017-03-09 48 views
1

我需要動態地插入社交嵌入,並且爲了運行腳本,我想將它們插入頭部,類似於jQuery的.html()正在做什麼。我將如何去編寫我可以注入其他組件的組件,但總會引用文檔的頭部?我嘗試這樣做:編寫只引用一個元素的單例組件

@Decorator(
    selector: 'head' 
) 
@Injectable() 
class ScriptLoader { 
    Element element; 

    ScriptLoader(this.element) { 
    } 

    loadScript(String url) { 
     ScriptElement script = new ScriptElement(); 
     script.src = url; 
     script.setAttribute("async", ""); 
     script.onLoad.listen((Event e) { 
      script.remove(); 
     }); 
     element.append(script); 
    } 
} 

和加載頁面時,this.element是頭一個參考,但是當它被注入到其他組件,它與錯誤No provider found for Element! (resolving ExecuteBindHTML -> ScriptLoader -> ScriptLoader -> Element)拋出。我將如何去實現這樣的組件?我不想使用querySelectors(因爲Angular)。

回答

1

您可以直接在構造函數中使用querySelector獲取頭元素。

@Injectable() 
class ScriptLoader { 
    Element element; 

    ScriptLoader() { 
    element = querySelector("head"); 
    } 
} 

然後直接將ScriptLoader類添加到引導方法。

相關問題