若是你曾經參與過Angular項目的開發,那麼你可能一眼就會看出誰將是本文的主角:html
<input type="text" [value]="value" #name>
若你對此陌生,也無須在乎。示例代碼的<input>
標籤的屬性中存在一個畫風明顯與其餘屬性不一樣的傢伙——#name
,這種以一個#
開頭命名,被附加在DOM元素上的屬性,被稱爲模板引用變量(template reference variables)。web
那麼何爲模板引用變量呢?文檔是這樣描述的:app
A template reference variable is often a reference to a DOM element within a template. It can also be a reference to an Angular component or directive or a web component.
模板引用變量能夠是Angualr模板中的DOM元素、Angular組件(指令),甚至Web組件的引用,而它具體是什麼,則取決於它所依附的元素(不使用指令進行干預時)。如前文示例代碼中的模板引用變量name
就是<input>
這一DOM元素的引用。code
既然模板引用變量是模板中某一元素的引用,那理所固然地咱們即可以經過這個引用變量" 觸及 "該模板元素的" 實體 "。這在實際地開發中是十分實用的,考慮如下代碼:component
<app-component #component [input]="variable"></app-component> {{ component.input }} {{ component.func() }}
經過模板引用變量咱們得到了app-component
組件的實例引用,這使得咱們能夠輕鬆地在模板中訪問app-component
組件內部的成員。在某些情境下,這種能力給咱們的開發提供了很大的助力。htm
You can refer to a template reference variable anywhere in the template.
在文檔中,官方絕不含糊地向咱們表示:模板引用變量能夠在模板中的任何地方使用。最騷的是,「任何地方」還被特別加粗。咱們在大多數的時候,並不會對這句話產生疑問,但也許某天你會懷疑這個anywhere是否真實。有以下的代碼:對象
<app-card> <ng-template #body> <app-component #component [input]="variable"></app-component> </ng-template> <ng-template #footer> {{component.input}} </ng-template> </app-card>
當代碼運行後,咱們將會在控制檯看到這樣的錯誤提示:element
TypeError: Cannot read property 'input' of undefined
爲何component
會是undefined?作用域
答案其實很明顯,模板引用對象能夠在模板中的任何地方使用,但此例中component
的定義與使用卻並不在一個template中。文檔中所描述的 template 並不能直接與 組件的模板文件 劃上等號。當咱們使用ng-template
時,會在當前模板的內部再創建一個新的模板,它的內部沒法直接被外部模板觸及,所以示例中的component.input
天然會引發錯誤。開發
當 template 的定義明確之後,一切都是如此簡單:模板引用變量存在做用域,其做用域是它所處的 template,而非它所在的模板文件,同時它能夠在其做用域內的任何地方被使用。
最後,咱們再看一個例子:
<div *ngIf="true"> <app-component #component [input]="variable"></app-component> </div> {{component.input}}
當這段代碼運行後,咱們依舊會在控制檯看到:
TypeError: Cannot read property 'input' of undefined
至於背後的緣由,我便做爲小小的懸念留給你們,由你們本身去了解。