Reputation: 722
I need to dynamically insert social embeds and in order to run scripts, I want to insert them into head, similar to how jQuery's .html()
is doing. How would I go about writing component that I can inject into other components but will always reference head of document? I tried this:
@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);
}
}
and when page is loaded, this.element
is a reference to head but when it is injected into other component, it throws with error No provider found for Element! (resolving ExecuteBindHTML -> ScriptLoader -> ScriptLoader -> Element)
. How would I go about implementing such component? I don't want to use querySelectors (because Angular).
Upvotes: 1
Views: 195
Reputation: 5924
You can get the head element with querySelector
directly in the constructor.
@Injectable()
class ScriptLoader {
Element element;
ScriptLoader() {
element = querySelector("head");
}
}
Then add the ScriptLoader
class to the bootstrap method directly.
Upvotes: 1