Angular应用里的Template Reference Variable,模板引用变量,用于创建一个对模板里DOM元素或者Angular指令的引用。
使用#号定义一个模板引用变量。
看个具体的例子:
<input #phone placeholder=“phone number” />
定义了一个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.