将ViewContainerRef
注入指令时,它绑定到什么元素?
例如,如果我们有一个模板:
template `<div><span vcdirective></span></div>`
vcdirective
的构造函数如下:
constructor(vc: ViewContainerRef) {
}
是vc:ViewContainerRef
绑定到span
元素的元素吗?
答案 0 :(得分:4)
是的,它将绑定到span元素。如果在构造函数中控制台vc,则会看到ViewContainerRef对象,检查它的element属性,您将在其中找到 span 。但是,当您将视图附加到容器中时,它将被附加到span旁边,而不是插入到其中,并且span将被挂起。
答案 1 :(得分:1)
是的,它一定会跨越。 ViewContainerRef
代表一个可以附加一个或多个视图的容器。我们可以使用诸如createEmbeddedView()
和createComponent()
之类的方法。 ViewContainerRef
用于构建动态组件。
答案 2 :(得分:0)
请检查此内容以更好地理解。它是一个可以附加到另一个元素的占位符。检查https://netbasal.com/angular-2-understanding-viewcontainerref-acc183f3b682
类似:
@Component({
selector: 'vcr',
template: `
<template #tpl>
<h1>ViewContainerRef</h1>
</template>
`,
})
export class VcrComponent {
@ViewChild('tpl') tpl;
constructor(private _vcr: ViewContainerRef) {
}
ngAfterViewInit() {
this._vcr.createEmbeddedView(this.tpl);
}
}