【问题标题】:custom structure directive in Angular2 documentationAngular2 文档中的自定义结构指令
【发布时间】:2017-12-11 06:57:23
【问题描述】:

在以下链接的自定义结构指令示例中,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 是什么?通常我会添加一个&lt;ng-container&gt; 作为视图容器?在示例中它来自哪里?

【问题讨论】:

    标签: angular


    【解决方案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 标签或 Component 指令 附在吗?

    它“有点”指向指令附加到的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
      }
    }
    

    【讨论】:

    • 好的,但示例中的ViewContainerRef 是什么? :) 谢谢
    • 指令宿主元素,ng-template标签转化成的DOM注释节点
    猜你喜欢
    • 2016-07-16
    • 1970-01-01
    • 1970-01-01
    • 2019-05-30
    • 1970-01-01
    • 2023-04-01
    • 2016-11-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多