How to Fix ExpressionChangedAfterCheckedError in Angular
ExpressionChangedAfterCheckedError happens when Angular detects a value change after it has checked the component's view. To fix it, update values inside lifecycle hooks like ngAfterViewInit or use ChangeDetectorRef.detectChanges() to notify Angular of changes safely.Why This Happens
This error occurs because Angular runs change detection twice to ensure the view is stable. If a value changes between these checks, Angular throws ExpressionChangedAfterCheckedError to warn you that the view is inconsistent.
It usually happens when you update a component property during or after Angular's change detection cycle, for example inside ngOnInit or a setter that affects the template.
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-broken', template: `<p>{{message}}</p>` }) export class BrokenComponent implements OnInit { message = 'Hello'; ngOnInit() { this.message = 'Changed after check'; } }
The Fix
To fix this, move the value update to ngAfterViewInit, which runs after Angular's initial change detection. Alternatively, inject ChangeDetectorRef and call detectChanges() after updating the value to inform Angular about the change.
import { Component, AfterViewInit, ChangeDetectorRef } from '@angular/core'; @Component({ selector: 'app-fixed', template: `<p>{{message}}</p>` }) export class FixedComponent implements AfterViewInit { message = 'Hello'; constructor(private cdr: ChangeDetectorRef) {} ngAfterViewInit() { this.message = 'Changed safely after check'; this.cdr.detectChanges(); } }
Prevention
To avoid this error, update component properties before Angular runs change detection or inside lifecycle hooks that run after view initialization like ngAfterViewInit. Avoid changing values in ngOnInit if they affect the template.
Use ChangeDetectorRef methods carefully to trigger change detection manually when needed. Also, consider using OnPush change detection strategy for better control.
Related Errors
Similar errors include:
- ExpressionChangedAfterItHasBeenCheckedError: Happens in development mode when a binding changes after Angular's check.
- ChangeDetectionError: General errors related to change detection cycles.
Quick fixes usually involve moving updates to later lifecycle hooks or using ChangeDetectorRef.