指令的元素是否已在ViewContainerRef上声明为指令?

时间:2019-02-07 00:19:01

标签: angular typescript angular-material

当我们的构造函数在指令中注入ViewContainerRef时,ViewContainerRef是声明该指令的元素。

例如<p [someDirective]="value"></p>

使用构造函数注入:

constructor(vc: ViewContainerRef) {
    //The ViewContainerRef is bound to the p element
}

如果我们现在进行vc.createComponent(...),是否会在p元素内创建该组件?

1 个答案:

答案 0 :(得分:1)

  

当我们的构造函数在指令中注入ViewContainerRef时,ViewContainerRef是声明该指令的元素。

是的,它引用了指令所引用的相同DOM元素。

例如:

@Directive({...})
public constructor MyDirective {
    public cosntructor(el: ElementRef, view: ViewContainerRef) {
        console.log(el.nativeElement === view.element.nativeElement); // prints TRUE
    }
}
  

如果我们现在执行vc.createComponent(...),将在p元素内创建该组件吗?

是的,因为ViewContainerRef具有许多视图。它具有lengthget(index: number)方法,可让您获取附加视图的ViewRef

因此您可以多次调用vc.createComponent(...),并且此ViewContainerRef将添加更多视图。添加的视图是新组件中的主机视图

相关问题