首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >为什么即使ViewContainerRef中有其他组件,它的长度也是0

为什么即使ViewContainerRef中有其他组件,它的长度也是0
EN

Stack Overflow用户
提问于 2017-03-02 09:03:37
回答 1查看 680关注 0票数 4

我有一个简单的组件:

代码语言:javascript
运行
复制
export class AppComponent implements AfterViewInit {
  constructor(private vc: ViewContainerRef) {}

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

template

代码语言:javascript
运行
复制
<h1>Hello {{name}}</h1>
<green></green>

因此,这里显然有green组件在ViewContainerRef of AppComponent中创建的主机视图。那么为什么lenght等于0呢?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-07-29 18:29:21

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

下面是一个例子。父AppComponent创建一个嵌入视图并使用a-comp元素,该元素是作为视图容器的AComponent的宿主元素:

代码语言:javascript
运行
复制
@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中,您将得到length of 1

代码语言:javascript
运行
复制
export class AComponent {
    name = 'A component';

    constructor(private vc: ViewContainerRef) {}

    ngAfterViewInit() {
        console.log(this.vc.length); // 1
    }
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42550933

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档