Performance: Template reference for direct access
This affects interaction speed and rendering efficiency by reducing the need for extra DOM queries or component lookups.
<input #inputRef />
<button (click)="inputRef.focus()">Focus Input</button>import { ElementRef, ViewChild, Component } from '@angular/core'; @Component({ selector: 'app-example', template: `<input #inputRef />` }) export class ExampleComponent { @ViewChild('inputRef') inputElement!: ElementRef; focusInput() { this.inputElement.nativeElement.focus(); } }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| @ViewChild querying | Extra DOM query during lifecycle | 0-1 reflows depending on usage | Minimal paint cost | [!] OK but slower |
| Template reference direct access | No extra DOM query, direct reference | 0 reflows | Minimal paint cost | [OK] Good |
#templateReference in Angular templates?inputBox on an <input> element?#inputBox is valid syntax for template references on elements.<input #myInput type="text"> <button (click)="myInput.focus()">Focus</button>
#myInput references the input element, allowing direct access to its DOM methods.myInput.focus(), which sets keyboard focus on the input element.<input #userInput type="text"> <button (click)="logValue()">Log</button>
logValue() {
console.log(userInput.value);
}userInput is undefined in the classuserInput in the class without passing it causes an error.#inputRef, which template code correctly implements this behavior?inputRef.value = '' clears the input content.clear() is undefined in the component, and clear() and reset() are not methods on input elements.Pass the test and this pattern moves unknown