2017-07-07 56 views
1

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

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>作为视图容器?这个例子来自哪里?

回答

1

这个例子

<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

所以将templateRef指向HTML标记或Com指示 是否附属于?

它“排序”指向指令所附的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 
    } 
} 
+0

好,但什么是'ViewContainerRef'的例子吗? :)感谢 – yurzui

+0

这是一个指令主机元素,一个DOM注释节点,它将'ng-template'标签转换成 –