2017-07-07 57 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'標籤轉換成 –