Angular Material mat-selection-list在重新加载时抛出ExpressionChangedAfterItHasBeenCheckedError

问题描述 投票:3回答:2

我有关于mat-selection-list和反应形式的问题。问题是我创建了mat-selection列表,然后在我从本地存储中读取后我更新了我的表单。一切正常但我得到了ExpressionChangedAfterItHasBeenCheckedError,因为它显然是用默认值创建的。这是预期的行为,如果它是:)我该如何解决它

你可以在这里看到叠加闪电战的例子: https://stackblitz.com/edit/angular-ul58q4

angular angular-material
2个回答
2
投票

此错误是因为您设置了表单初始值但视图无法检测到它,因此在设置初始值后使用changeDetectorRef它将是正确的:

import { Component, AfterViewInit, Injectable ,ChangeDetectorRef } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { LocalStorageService } from './local-storage.service';

const FILTER_FORM_STORAGE_KEY = 'filterFormStorageKey';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit {
  formGroup: FormGroup;
  typesControl: FormControl;

  types: any[] = [
    { id: 1, name: 'Type A' },
    { id: 2, name: 'Type B' }
  ];

  constructor(private _storage: LocalStorageService,
  private changeDetectorRef: ChangeDetectorRef) {
    this.formGroup = new FormGroup({
      typesControl: this.typesControl = new FormControl(null, [Validators.required])
    });
  }

  ngAfterViewInit(): void {
    const formStorage = this._storage.get(FILTER_FORM_STORAGE_KEY);
    if (formStorage) {
      this.formGroup.patchValue(formStorage);
    }
    this.changeDetectorRef.detectChanges();
  }

  saveForm() {
    console.log('submitted');
    this._storage.set(FILTER_FORM_STORAGE_KEY, this.formGroup.value);   
  }
}

工作DEMO


1
投票

我们无法在stackblitz中查看源代码。问题是您在更新DOM后更新组件对象。您还需要手动触发更改检测以更新DOM。使用

setTimeout(()=>{

}, 0);
© www.soinside.com 2019 - 2024. All rights reserved.