ExpressionChangedAfterItHasBeenCheckedError with Ngrx

I know this may be encountered several times but I can't find a clean efficient way to solve it. I have a piece of code like this <div *ngIf="userUsername$ | async as username"></div> and when I run I get this

ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'ngIf: [object Object]'. Current value: 'ngIf: admin'.

in my component.ts userUsername$ = this.store.pipe(select(selectSelectedUsername));

Is there any efficient way to fix this rather than setTimeout?

Thank you,

UPDATE

entire component's code as requested

import { Component, OnInit, ChangeDetectorRef, ChangeDetectionStrategy, OnDestroy } from '@angular/core';
import { select, Store } from '@ngrx/store';
import { selectSelectedUsername } from '../state-management/selectors/user.selector';
import { IAppState } from '../state-management/state/app.state';

@Component({
  selector: 'my-layout',
  templateUrl: './layout.component.html',
  styleUrls: ['./layout.component.sass']
})
export class LayoutComponent implements OnInit, OnDestroy {

  userUsername$ = this.store.pipe(select(selectSelectedUsername));

  constructor(
    private store: Store<IAppState>
  ) {
  }

  ngOnInit() { }

  ngOnDestroy() { }

}

1 answer

  • answered 2019-10-16 04:01 Prakash Harvani

    if you want to solve this error so you can use this

    import {ChangeDetectorRef } from '@angular/core';
    
      constructor(
        title: Title,
        private cdr: ChangeDetectorRef){ }
    
    
     this.cdr.detectChanges();
    

    Note:****After your variable value changed to use this line
    this.cdr.detectChanges();