Performance: Template reference variables
Template reference variables affect DOM access and event handling performance by providing direct references to elements or components without extra queries.
<input #myInput type="text"> <button (click)="handleClick(myInput.value)">Click</button> handleClick(value: string) { console.log(value); }
handleClick() {
const input = document.querySelector('#myInput');
console.log(input.value);
}| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Using document.querySelector in event handlers | 1 DOM query per event | 1 reflow per event | Low | [X] Bad |
| Using Angular template reference variables | No extra DOM queries | 0 reflows per event | Low | [OK] Good |
template reference variable in Angular templates?inputBox on an <input> element?#variableName syntax to declare template reference variables.#inputBox which is correct.<input #myInput type="text"> <button (click)="alert(myInput.value)">Show Value</button>
#myInput variable refers to the input element. Accessing myInput.value gets the current text typed.alert(myInput.value), so it shows the input's current value.<input #userInput type="text"> <button (click)="logValue()">Log</button>
logValue() {
console.log(userInput.value);
}userInput directly, which is undefined in the class, causing an error.<input #myInput type="text"> <button (click)="???">Reset</button>
????myInput.value = '' clears the input. Using this or calling reset() method is incorrect here.Pass the test and this pattern moves unknown