0

I am looking for a way to get the AppComponent ViewContainerRef from a service.

I have found code online such as this code, this code or this issue, but they all are for previous versions of Angular (I am using version 6).

I would like to get this reference without having to set it myself through a setter.

Right now, I have to inject ViewContainerRef into AppComponent and give it to the service.

I would like to get the reference from nothing but an injected provider directly in the service, something along the lines of

  constructor(
    private applicationRef: ApplicationRef
  ) {
    this.viewContainerRef = applicationRef.getAppViewRef();
  }

The use-case is to create components and append them to the document, at body level or AppComponent level ; this would allow me to create notifications, dialogs ...

2 Answers2

1

You could use it exactly like in the link you provided. I created a stackblitz here: https://angular-5lhjkq.stackblitz.io In the AppService I inject the ApplicationRef and with attachViewI add a DummyComponent in AppComponent to the body to and to the angular app.

This works seems to work exactly like in past versions.

Christian S.
  • 295
  • 1
  • 2
  • 12
  • The last part of that is setting me off : `const element = (newComponentInstance.hostView as EmbeddedViewRef) .rootNodes[0] as HTMLElement; document.body.appendChild(element);`. This doesn't seem natural and it isn't what's exposed in [the documentation](https://angular.io/guide/dynamic-component-loader#resolving-components). That's why I was asking for another way, in Angular 6, using the `ViewContainerRef`. –  Aug 31 '18 at 06:30
  • I found this, but I am not sure if it still works: https://stackoverflow.com/questions/37660584/how-to-get-root-viewcontainerref-of-angular2-aplication – Christian S. Aug 31 '18 at 18:22
0

Since I can't close my question, I am answering it.

For those that look for something similar Thoughtram's Dominic Elm made a very good example of use of CDK's Overlays and Portals.

Instead of looking for a reference to the root component, I'm going to append components dynamically to the application through that.