我有一个简单的组件:
export class AppComponent implements AfterViewInit {
constructor(private vc: ViewContainerRef) {}
ngAfterViewInit(): void {
this.vc.lenght; // 0
}
和template
<h1>Hello {{name}}</h1>
<green></green>
因此,这里显然有green
组件在ViewContainerRef
of AppComponent
中创建的主机视图。那么为什么lenght
等于0
呢?
发布于 2017-07-29 18:29:21
在ViewContainerRef
构造函数中注入的AppComponent
不是AppComponent
子组件/视图元素的容器。它实际上属于父组件,因此是父组件子嵌入视图的容器。因为父组件没有嵌入式视图,所以它的长度是0
。但是,如果父组件具有嵌入的视图,则会看到其他数字。
下面是一个例子。父AppComponent
创建一个嵌入视图并使用a-comp
元素,该元素是作为视图容器的AComponent
的宿主元素:
@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
export class AComponent {
name = 'A component';
constructor(private vc: ViewContainerRef) {}
ngAfterViewInit() {
console.log(this.vc.length); // 1
}
}
https://stackoverflow.com/questions/42550933
复制相似问题