:
- , ElementRef.
- , ( API )
- , AppComponent.
, , AppComponent ElementRef. (Angular 6.1)
private readonly rootRef: ElementRef;
constructor(private appRef: ApplicationRef) {
this.rootRef = appRef.components[0].injector.get(ElementRef);
}
Later, I discovered that if I tried to deploy and use the service very early after Angular bootstrap, an exception occurred because it appRef.componentswas still empty. So instead, I changed the code to make a rootRefpromise that resolves with ElementRef. Thus, the consumer code can call it immediately without causing an exception, but it will have to wait for permission ElementRef:
private readonly rootRef: Promise<ElementRef>;
constructor(appRef: ApplicationRef) {
this.rootRef = new Promise(resolve => {
setTimeout(
() => resolve(appRef.components[0].injector.get(ElementRef)),
100
);
});
}
source
share