user4676340
user4676340

Reputation:

Get AppComponent ViewContainerRef

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 ...

Upvotes: 0

Views: 1627

Answers (2)

user4676340
user4676340

Reputation:

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.

Upvotes: 0

Christian S.
Christian S.

Reputation: 293

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.

Upvotes: 1

Related Questions