Translated value inside mat-option causes ExpressionChangedAfterItHasBeenCheckedError when lang is changed

Viewed 496

Select a value inside the mat-select, then click on the switch button.

You should see an 'ExpressionChangedAfterItHasBeenCheckedError' from the console

https://stackblitz.com/edit/angular-ivy-ifbsaj

It happens since I have migrated my project from Angular 11 to Angular 12

2 Answers

Injecting the ChangeDetectorRef into your component, and calling the detectChanges function after changing the language within switchLang, will force the Angular to detect the values that have changed after it was checked.

constructor(
  private _translateService: TranslateService,
  private cdr: ChangeDetectorRef
) {}

switchLang() {
  this._translateService.use(
    this._translateService.currentLang == 'fr' ? 'en' : 'fr'
  );
  this.cdr.detectChanges();
}

I have the same problem. I found 2 workarounds. The easiest way is to turn the mat-select tag into a native select one.

If, on the other hand, you wish to keep using the mat-select element, then you can do something like this:

// inside some component
constructor(private translate: TranslateService) {}

ngOnInit(): void {
    this.translate.get(["my.dropdown.keys"]).subscribe(v => {
        this.values = [
            { label: v["value1"], value: "value1" },
            { label: v["value2"], value: "value2" },
            { label: v["value3"], value: "value3" },
        ];
    });
}

Then, in your .html file, you can just use an *ngFor directive to populate your options.

Related