天天看點

Angular應用裡的Template Reference變量

Angular應用裡的Template Reference Variable,模闆引用變量,用于建立一個對模闆裡DOM元素或者Angular指令的引用。

使用#号定義一個模闆引用變量。

看個具體的例子:

定義了一個phone變量,指向input html元素。

在Component html模闆的任意地方,都可以直接通路模闆引用變量。

<input #phone placeholder="phone number" />

<!-- lots of other elements -->

<!-- phone refers to the input element; pass its `value` to an event handler -->
<button (click)="callPhone(phone.value)">Call</button>      

If you declare the variable on a component, the variable refers to the component instance.

If you declare the variable on a standard HTML tag, the variable refers to the element.

If you declare the variable on an element, the variable refers to a TemplateRef instance, which represents the template.

If the variable specifies a name on the right-hand side, such as #var=“ngModel”, the variable refers to the directive or component on the element with a matching exportAs name.

模闆引用變量的生命周期是整個模闆,這一點同模闆輸入變量,比如*ngFor裡的(let phone)不同,是以需要注意命名沖突。

除了#之外,另一種等價的文法是ref-fax,相當于#ref.

繼續閱讀