Angular2 文档中的自定义结构指令



在以下链接的自定义结构指令示例中,TemplateRef 和 ViewContainerRef 指向什么?

https://angular.io/guide/structural-directives#unless

指令通常没有视图。那么 templateRef 会指向指令附加到的 HTML 标记或组件吗?例如,在下面的代码中,模板是介于<p> ...</p>?我读到*被转换为<ng-template>所以可能是这样。

<p *myUnless="condition">Show this sentence unless the condition is true.</p>

示例中的 ViewContainerRef 是什么?通常我会添加一个<ng-container>作为视图容器?在示例中,它从何而来?

这个例子

<p *myUnless="condition">Show this sentence unless the condition is true.</p>

由编译器转换为

<ng-template [myUnless]="condition">
<p>Show this sentence unless the condition is true.</p>
<ng-template>

所以你现在可以看到myUnless指令被放置在ng-template元素上,这就是为什么它可以访问templateRef

所以模板引用会指向 HTML 标记或组件指令 是依附的?

它"有点"指向指令附加到的ng-template元素的内容。在后台,它引用为ng-template内容创建的嵌入式视图定义。

示例中的 ViewContainerRef 是什么?

任何 HTML 元素都可以充当视图容器。因此,在这种情况下,指令注入引用指令主机元素的视图容器。

ng-template元素呈现为注释 DOM 节点,因此您将看到ViewContaineRefTemplateRef都指向此注释节点:

export class MyUnless {
constructor(t: TemplateRef<any>, vc: ViewContainerRef) {
console.log(t.elementRef.nativeElement.nodeName); // #comment
console.log(t.elementRef.nativeElement === vc.element.nativeElement); // true
}
}

最新更新