简体   繁体   中英

ExpressionChangedAfterItHasBeenCheckedError during dynamic template management in Angular

I need to dynamically manage templates. I want to show or hide some view based on the parameter which is changed after WebSocket message or user interacition. I use ngIf for this, but sometimes (especialy, when I reload the view, and messages comes quickly) console receive me an error

ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'ngIf: true'. Current value: 'ngIf: false'.

I user Angular 8

Main Component

export class MainComponent implements AfterViewInit, OnInit {

 public view_config;

 constructor(public pluginInfoService: PluginInfoService){}

 ngOnInit() {
   this.pluginInfoService.getViewConfig().subscribe(view_config => {
     this.view_config = view_config;
   });
 }

}

Main Component Template

<popup-window *ngIf="view_config.show_popup_window" class="overflow_hidden h-100 w-100" [view_config]="view_config">
  <select-media *ngIf="view_config.popup_window_mode == 'select_media'" [view_config]="view_config" class="container-fluid h-100"></select-media>
  <get-contact-name *ngIf="view_config.popup_window_mode == 'get_contact_name'" [view_config]="view_config" class="container-fluid h-100"></get-contact-name>
  <chat-view *ngIf="view_config.popup_window_mode == 'chat_view'" class="container-fluid h-100 flex-column d-flex p-0"></chat-view>
  <change-media-invitation *ngIf="view_config.popup_window_mode == 'media_change_invite'" [view_config]="view_config" class="container-fluid h-100"></change-media-invitation>
</popup-window>

Plugin Info Servie

export class PluginInfoService {

  private view_config = {
    show_main_button: true,
    show_popup_window: true,
    popup_window_mode: 'select_media',
    show_popup_media_window: false,
    popup_media_window_mode: null,
    minimize_popup_window: false
  };

  private viewConfigStream = new BehaviorSubject(this.view_config);

  constructor() {
  }

  setViewConfigParam(param, value) {
    this.view_config[param] = value;
    this.viewConfigStream.next(this.view_config);
  }

  getViewConfig(): Observable<any> {
    return this.viewConfigStream.asObservable();
  }
}

The mechanism already works, but I suppose it makes more problems around it. Firstly I don't want have this errors, secondly I want to be sure that all is implemented properly. How to fix this problem ? Is this method is good ?

If you want to avoid possible changes to the views whilst the lifecycle is still in the process of generating the page you could simply hook into a later point, eg

replace

ngOnInit()

with

ngAfterViewInit()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM