CodexBloom - Programming Q&A Platform

Angular 15: Intermittent 'ExpressionChangedAfterItHasBeenCheckedError' When Using ngIf with Async Pipe

👀 Views: 32 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-12
angular rxjs async-pipe ngIf TypeScript

I'm experiencing an intermittent scenario with Angular 15 where I get an `ExpressionChangedAfterItHasBeenCheckedError` when toggling a component's display based on an observable value using `ngIf` with the async pipe... The observable provides a boolean value that determines whether a particular section of the template should be displayed or not. Here's a simplified version of what I have: ```typescript import { Component } from '@angular/core'; import { BehaviorSubject } from 'rxjs'; @Component({ selector: 'app-example', template: ` <div *ngIf="showSection$ | async">This is the toggled section!</div> <button (click)="toggleSection()">Toggle Section</button> ` }) export class ExampleComponent { private showSectionSubject = new BehaviorSubject<boolean>(false); showSection$ = this.showSectionSubject.asObservable(); toggleSection() { this.showSectionSubject.next(!this.showSectionSubject.value); } } ``` At times when I click the button to toggle the section, I see the behavior message in the console: ``` behavior: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'false'. Current value: 'true'. ``` I've tried wrapping the `toggleSection` method in `setTimeout` to delay the change and mitigate the behavior, but it feels like more of a workaround than a solution. Is there a more reliable way to handle this situation without running into the `ExpressionChangedAfterItHasBeenCheckedError`? What best practices should I follow when using observables with `ngIf`? Any insights or suggestions would be greatly appreciated! This is for a application running on Ubuntu 20.04. Thanks, I really appreciate it!