即使内部包含其他组件,为什么ViewContainerRef的长度也为0 [英] Why the length of the ViewContainerRef is 0 even if it has other components inside
问题描述
我有这个简单的组件:
export class AppComponent implements AfterViewInit {
constructor(private vc: ViewContainerRef) {}
ngAfterViewInit(): void {
this.vc.lenght; // 0
}
和template
:
<h1>Hello {{name}}</h1>
<green></green>
因此,在这里我显然具有由AppComponent
的ViewContainerRef
内部的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
中,您将获得1
的length
:
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屋!