3

loadNextToLocation now expects a ViewContainerRef, any ideas on how to get the root viewContainerRef of the application in a correct way?

thanks in advance.

Update:

i want to get root viewContainerRef from any class or any component

Frank N
  • 9,625
  • 4
  • 80
  • 110
Bahgat Mashaly
  • 510
  • 7
  • 15

2 Answers2

17

OLD WAY: Angular 2.0.0-rc.3

This is a total hack and is in no way the correct way to get the root ViewContainerRef, but I was unable to find an official way to do this. Since these are not public properties they can change at any time and this method would no longer work. This method still works as of 2.0.0-rc.3.

class SomeComponent {
    constructor(private appRef: ApplicationRef) { }
    let viewRef: ViewContainerRef = appRef['_rootComponents'][0]['_hostElement'].vcRef;
}

There is also currently an open issue for this on GitHub: https://github.com/angular/angular/issues/9293

UPDATE: Angular 2.4.2

The above method won't work with the later versions of Angular (as of 2.4.2).

The method I use now is this:

In the root component pass the ViewContainerRef so you can reference it later:

class AppComponent {
    constructor(public viewRef: ViewContainerRef) { }
}

And then in the component or service that you want to get the root ViewContainerRef:

class SomeOtherComponent {
    constructor(private appRef: ApplicationRef) { }

    let viewRef = (appRef.components[0].instance as AppComponent).viewRef;
}

The above will bring in the instance of your root component, and since you injected the ViewContainerRef in the constructor (and made it public) you can now reference it directly.

Daniel Sara
  • 311
  • 1
  • 4
2

I haven't tried it with the root component myself yet but I assume it works the same as with other components:

class AppComponent {
  constructor(private vcRef:ViewContainerRef) {}
}
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • thanks Günter Zöchbauer , it work from another Component than AppComponent many thanks Günter Zöchbauer – Bahgat Mashaly Jun 06 '16 at 15:06
  • Then set it on a shared service and acquire it from that service where you need it. As far as I know there is no official way to get `ViewContainerRef` from the root component from outside the root component. – Günter Zöchbauer Jun 06 '16 at 15:08
  • sorry it doesn't work , i can't edit my comment you are right , i should keep root ViewContainerRef in memory until i need it but is this the best solution ? – Bahgat Mashaly Jun 06 '16 at 15:13
  • What doesn't work? [**Plunker example**](https://plnkr.co/edit/WQklWK91Xtq26U1UUVax?p=preview). `ViewContainerRef` of your root component will be kept in memory anyway as long as the Angular2 application runs. The only thing you get is a reference. – Günter Zöchbauer Jun 06 '16 at 15:19