18. Handling User Input (Reference Variables)
In addition to event binding, Angular provides template reference variables for direct access to DOM elements or component instances within the template.
What is a Template Reference Variable?
A template reference variable is declared using the hash symbol (#) followed by the variable name (e.g., #usernameInput). It typically references the DOM element on which it is defined.
Example: Accessing Input Value
We can use a template reference variable to bypass event binding if we only need the final value on a click event.
html
<button (click)="saveData(userInput.value)">Save
Component Class:
typescript export class InputSaverComponent { savedName: string = '';
saveData(inputVal: string) {
this.savedName = inputVal;
console.log(Saved: ${this.savedName});
}
}
Referencing NgModel or a Component Instance
If the reference variable is defined on an element that hosts an Angular directive (like ngModel) or a component, the reference variable points to the instance of that directive or component, not just the DOM element.
html <input type="email" #emailControl="ngModel" [(ngModel)]="userEmail">
Email is required!
Here, #emailControl holds the NgModel instance, allowing us to access its state properties crucial for form validation.