在NgRx中使用FormControl的patchValue()方法时,出现“无法分配只读属性'_pendingValue'”的错误可能是因为在使用patchValue()之前,没有先调用markAsDirty()方法。
解决方法是先调用markAsDirty()方法,然后再使用patchValue()方法。下面是一个示例代码:
import { Component, OnInit } from '@angular/core';
import { FormControl } from '@angular/forms';
import { Store } from '@ngrx/store';
import { AppState } from '../../store/app.state';
import { UpdateFormValue } from '../../store/actions/form.actions';
@Component({
selector: 'app-your-component',
template: `
`,
})
export class YourComponent implements OnInit {
nameControl = new FormControl('');
constructor(private store: Store) {}
ngOnInit() {}
updateForm() {
this.nameControl.markAsDirty(); // 先调用markAsDirty()方法
this.store.dispatch(new UpdateFormValue({ name: this.nameControl.value })); // 使用patchValue()方法
}
}
在这个示例中,我们先调用了nameControl的markAsDirty()方法,然后在updateForm()方法中使用了patchValue()方法来更新表单的值。这样就可以避免“无法分配只读属性'_pendingValue'”的错误。