在 Angular 中,当我们使用 [(ngModel)] 绑定表单控件时,控件的值发生变化时会触发变更检测,并更新组件的视图。然而,有时候我们会遇到表单更新时出现奇怪的行为,比如视图没有更新,或者更新了但是值并没有更新。
这种情况通常是因为使用了对象引用,导致 Angular 没有识别出变化。解决办法是使用数组的 slice() 方法来复制对象,使其成为新的引用。示例如下:
// 原本的代码 this.users.push(newUser); this.selectedUser = newUser; this.form.patchValue({ name: newUser.name, age: newUser.age });
// 改为以下代码 this.users.push({...newUser}); this.selectedUser = {...newUser}; this.form.patchValue({ name: newUser.name, age: newUser.age });
这样就能够解决表单更新时出现的奇怪行为了。