Friday, 25 May 2018

Angular - Template reference variables (#var)

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.
Use the hash symbol (#) to declare a reference variable. The #phone declares a phone variable on an <input> element.
<input #phone placeholder="phone number">
You can refer to a template reference variable anywhere in the template. The phone variable declared on this <input> is consumed in a <button> on the other side of the template.
<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>

How a reference variable gets its value:
In most cases, Angular sets the reference variable's value to the element on which it was declared. In the previous example, phone refers to the phone number <input> box. The phone button click handler passes the input value to the component's callPhone method. But a directive can change that behavior and set the value to something else, such as itself. The NgForm directive does that.
The following is a simplified version of the form example in the Forms guide.
<form (ngSubmit)="onSubmit(heroForm)" #heroForm="ngForm">
  <div class="form-group">
    <label for="name">Name
      <input class="form-control" name="name" required [(ngModel)]="">
  <button type="submit" [disabled]="!heroForm.form.valid">Submit</button>
<div [hidden]="!heroForm.form.valid">
A template reference variable, heroForm, appears three times in this example, separated by a large amount of HTML. What is the value of heroForm?
If Angular hadn't taken it over when you imported the FormsModule, it would be the HTMLFormElement. The heroForm is actually a reference to an Angular NgForm directive with the ability to track the value and validity of every control in the form.
The native <form> element doesn't have a form property. But the NgForm directive does, which explains how you can disable the submit button if the heroForm.form.valid is invalid and pass the entire form control tree to the parent component's onSubmit method.

Template reference variable warning notes:
A template reference variable (#phone) is not the same as a template input variable (let phone) such as you might see in an *ngFor.
The scope of a reference variable is the entire template. Do not define the same variable name more than once in the same template. The runtime value will be unpredictable.
You can use the ref- prefix alternative to #. This example declares the fax variable as ref-fax instead of #fax.
<input ref-fax placeholder="fax number">
<button (click)="callFax(fax.value)">Fax</button>

No comments:

Post a Comment