即使内部包含其他组件,为什么ViewContainerRef的长度也为0 [英] Why the length of the ViewContainerRef is 0 even if it has other components inside

查看:69
本文介绍了即使内部包含其他组件,为什么ViewContainerRef的长度也为0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个简单的组件:

export class AppComponent implements AfterViewInit {
  constructor(private vc: ViewContainerRef) {}

  ngAfterViewInit(): void {
     this.vc.lenght; // 0
  }

template:

<h1>Hello {{name}}</h1>
<green></green>

因此,在这里我显然具有由AppComponentViewContainerRef内部的green组件创建的主机视图.为什么lenght等于0?

So here I clearly have host view created by green component inside ViewContainerRef of AppComponent. Why is lenght equal to 0 then?

推荐答案

您在AppComponent构造函数中注入的ViewContainerRef不是AppComponent子组件/视图元素的容器.它实际上属于父组件,因此是父组件子嵌入视图的容器.由于父组件没有嵌入式视图,因此其长度为0.但是,如果父组件具有嵌入式视图,您将看到其他数字.

The ViewContainerRef that you inject inside the AppComponent constructor is not the container for the AppComponent child components/view elements. It actually belongs to the parent component and hence is a container for the parent component child embedded views. Since parent component has no embedded views its length is 0. But if the parent component had the embedded views you would see other number.

这里是一个例子.父级AppComponent创建一个嵌入式视图,并使用a-comp元素(它是AComponent的宿主元素)作为视图容器:

Here is an example. The parent AppComponent creates an embedded view and uses a-comp element, which is the host element of the AComponent as a view container:

@Component({
    ...
    template: `
        <h2>Hello {{name}}</h2>
        <ng-template #t>I am embedded view</ng-template>
        <a-comp></a-comp>
    `
})
export class AppComponent {
    name = `Angular! v${VERSION.full}`;
    @ViewChild(AComponent, {read: ViewContainerRef}) acomp;
    @ViewChild('t', {read: TemplateRef}) t;

    constructor() {}

    ngOnInit() {
        this.acomp.createEmbeddedView(this.t);
    }
}

现在,如果将ViewContainerRef注入到AComponent中,您将获得1length:

And now if you inject ViewContainerRef into the AComponent you will get the length of 1:

export class AComponent {
    name = 'A component';

    constructor(private vc: ViewContainerRef) {}

    ngAfterViewInit() {
        console.log(this.vc.length); // 1
    }
}

这篇关于即使内部包含其他组件,为什么ViewContainerRef的长度也为0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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