Angular模板引用變量
如果你曾經參與過Angular項目的開發,那麼你可能一眼就會看出誰將是本文的主角:
<input type="text" [value]="value" #name>
若你對此陌生,也無須在意。示例代碼的<input>
標籤的屬性中存在一個畫風明顯與其他屬性不同的傢伙——#name
,這種以一個#
開頭命名,被附加在DOM元素上的屬性,被稱爲模板引用變量(template reference variables)。
那麼何爲模板引用變量呢?文檔是這樣描述的:
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元素的引用。
既然模板引用變量是模板中某一元素的引用,那理所當然地我們便可以通過這個引用變量" 觸及 "該模板元素的" 實體 "。這在實際地開發中是十分實用的,考慮以下代碼:
<app-component #component [input]="variable"></app-component>
{{ component.input }}
{{ component.func() }}
通過模板引用變量我們獲得了app-component
組件的實例引用,這使得我們可以輕鬆地在模板中訪問app-component
組件內部的成員。在某些情境下,這種能力給我們的開發提供了很大的助力。
模板引用變量的作用域
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>
當代碼運行後,我們將會在控制檯看到這樣的錯誤提示:
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
至於背後的原因,我便作爲小小的懸念留給大家,由大家自己去了解。