0
0
Angularframework~8 mins

Template reference variables in Angular - Performance & Optimization

Choose your learning style9 modes available
Performance: Template reference variables
MEDIUM IMPACT
Template reference variables affect DOM access and event handling performance by providing direct references to elements or components without extra queries.
Accessing an input element's value on a button click
Angular
<input #myInput type="text">
<button (click)="handleClick(myInput.value)">Click</button>

handleClick(value: string) {
  console.log(value);
}
Template reference variables provide direct access to the element without querying the DOM repeatedly.
📈 Performance GainNo extra reflows triggered on click, improving interaction speed
Accessing an input element's value on a button click
Angular
handleClick() {
  const input = document.querySelector('#myInput');
  console.log(input.value);
}
Direct DOM queries like document.querySelector run on every event, causing extra layout calculations and slower response.
📉 Performance CostTriggers 1 reflow per click event due to DOM query
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Using document.querySelector in event handlers1 DOM query per event1 reflow per eventLow[X] Bad
Using Angular template reference variablesNo extra DOM queries0 reflows per eventLow[OK] Good
Rendering Pipeline
Template reference variables are resolved during Angular's template compilation and runtime binding, allowing direct element or component access without extra DOM queries.
Template Compilation
Event Handling
Layout
⚠️ BottleneckEvent Handling stage can be slowed by repeated DOM queries if template references are not used
Core Web Vital Affected
INP
Template reference variables affect DOM access and event handling performance by providing direct references to elements or components without extra queries.
Optimization Tips
1Use template reference variables to access elements directly without DOM queries.
2Avoid document.querySelector or similar DOM queries inside event handlers.
3Reducing layout reflows during events improves interaction responsiveness (INP).
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance benefit of using Angular template reference variables over document.querySelector?
AThey reduce the initial page load time
BThey avoid repeated DOM queries during event handling
CThey improve CSS selector matching speed
DThey decrease JavaScript bundle size
DevTools: Performance
How to check: Record a performance profile while interacting with the element. Look for scripting time and layout events triggered by event handlers.
What to look for: High scripting time and layout events indicate costly DOM queries; minimal layout events indicate efficient template reference usage.