如何获得angular2应用的根viewContainerRef [英] how to get root viewContainerRef of angular2 aplication

查看:98
本文介绍了如何获得angular2应用的根viewContainerRef的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

loadNextToLocation现在需要一个ViewContainerRef,以及有关如何以正确方式获取应用程序的根viewContainerRef的任何想法?

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

提前谢谢.

更新:

我想从任何类或任何组件中获取root viewContainerRef

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

推荐答案

旧方法:Angular 2.0.0-rc.3

OLD WAY: Angular 2.0.0-rc.3

这是一个完全的黑客,绝不是获取根ViewContainerRef的正确方法,但是我找不到找到此方法的正式方法.由于这些不是公共财产,因此它们可以随时更改,并且该方法将不再起作用.此方法从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;
}

当前在GitHub上还有一个未解决的问题: https://github.com/角/角/问题/9293

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

更新:Angular 2.4.2

UPDATE: Angular 2.4.2

上述方法不适用于更高版本的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:

在根组件中传递ViewContainerRef,以便您以后可以引用它:

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

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

然后在要获取根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;
}

以上内容将引入您的根组件的实例,并且由于您将ViewContainerRef注入了构造函数(并将其公开),因此您现在可以直接引用它.

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.

这篇关于如何获得angular2应用的根viewContainerRef的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆