gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 18:22:44 26 4
gpt4 key购买 nike

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

你可以在这里看到堆栈 Blitz 的例子:
https://stackblitz.com/edit/angular-ul58q4

最佳答案

这个错误是因为你设置了表单初始值,但是 View 无法检测到它,所以在设置初始值后使用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 .

关于Angular Material mat-selection-list 在重新加载时抛出 ExpressionChangedAfterItHasBeenCheckedError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52112353/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com