Angular OnPush Change Detection Issues and Fixes

🔥 Angular Developers, Try This (Hardest Q&A) 🔥 Q: You have a component using "OnPush" change detection. Inside it, you update an object property like this: this.user.name = 'Zuber'; But the UI does NOT update. 👉 Why does this happen, and what are ALL the correct ways to fix it? --- A: This happens because "OnPush" change detection only checks for reference changes, not deep mutations. Updating "this.user.name" mutates the object but does NOT change its reference → Angular skips re-render. --- 💡 Correct Fixes: 1. ✅ Change the object reference this.user = { ...this.user, name: 'Zuber' }; 2. ✅ Use "ChangeDetectorRef" constructor(private cdr: ChangeDetectorRef) {} this.user.name = 'Zuber'; this.cdr.markForCheck(); 3. ✅ Use "detectChanges()" (force update) this.cdr.detectChanges(); 4. ✅ Use async pipe (best practice with Observables) {{ user$ | async }} 5. ✅ Emit new value via BehaviorSubject this.user$.next({ ...this.user, name: 'Zuber' }); --- ⚠️ Bonus Trap: Even "setTimeout()" or API calls WON’T update UI unless reference changes or CD is triggered. --- 💬 Most devs get this wrong in interviews. If you knew this already, you’re in top 5% Angular devs. #Angular #Frontend #WebDev #JavaScript #InterviewQuestions

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories