0
0
Angularframework~8 mins

Loading states and error patterns in Angular - Performance & Optimization

Choose your learning style9 modes available
Performance: Loading states and error patterns
MEDIUM IMPACT
This concept affects how quickly users see feedback during data fetching and error handling, impacting perceived responsiveness and visual stability.
Showing loading feedback while fetching data
Angular
template: `<div aria-live="polite">{{ isLoading ? 'Loading...' : data }}</div>`
component: fetchData() { this.isLoading = true; this.http.get(...).subscribe(res => { this.data = res; this.isLoading = false; }); }
Using a single container with text swap avoids DOM node removal, reducing layout shifts.
📈 Performance GainSingle reflow, minimal CLS, better INP due to stable layout
Showing loading feedback while fetching data
Angular
template: `<div *ngIf="isLoading">Loading...</div><div *ngIf="!isLoading">{{data}}</div>`
component: fetchData() { this.isLoading = true; this.http.get(...).subscribe(res => { this.data = res; this.isLoading = false; }); }
Conditional rendering removes and adds DOM nodes causing layout shifts and multiple reflows.
📉 Performance CostTriggers 2 reflows per load cycle and causes CLS due to content jumping
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Conditional *ngIf loading/error blocksAdds/removes nodes2+ per toggleHigh due to layout shifts[X] Bad
Single container with text swapText content change only1 per toggleLow, stable layout[OK] Good
Rendering Pipeline
Loading and error states affect the Layout and Paint stages by adding or removing DOM nodes or changing text content, which can cause reflows and repaints.
Layout
Paint
Composite
⚠️ BottleneckLayout due to DOM node insertion/removal causing reflows
Core Web Vital Affected
INP, CLS
This concept affects how quickly users see feedback during data fetching and error handling, impacting perceived responsiveness and visual stability.
Optimization Tips
1Avoid adding/removing DOM nodes for loading and error states; update text content instead.
2Use ARIA live regions to announce loading and error changes for accessibility without layout shifts.
3Keep containers stable to prevent layout recalculations and improve visual stability.
Performance Quiz - 3 Questions
Test your performance knowledge
Which pattern reduces layout shifts when showing a loading state in Angular?
AUse *ngIf to add/remove loading div
BUse a single container and swap text content
CAdd loading spinner as a separate DOM node each time
DReload the entire component on loading
DevTools: Performance
How to check: Record a session while triggering loading and error states. Look for Layout and Recalculate Style events in the flame chart.
What to look for: Multiple layout events and long tasks indicate costly DOM changes; minimal layout events show efficient updates.