angular - 表单组值更改时不会触发更改检测
问题描述
我创建了一个简单的示例来演示我面临的一个奇怪的问题。
Stackblitz - https://stackblitz.com/edit/angular-change-detection-form-group
我有三个组件,它们是:
1 - 应用程序组件
import { Component, OnInit, ChangeDetectionStrategy } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
@Component({
selector: 'my-app',
template: `<hello [form]="form"></hello>
<hr />
<button (click)="changeFormValue()">Change Form Value</button>`,
styleUrls: ['./app.component.css'],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class AppComponent implements OnInit {
name = 'Angular';
form: FormGroup;
ngOnInit() {
this.form = new FormGroup({
name: new FormControl('ABC'),
age: new FormControl('24')
});
}
changeFormValue() {
this.form.setValue({
name: 'XYZ',
age: 35
})
}
}
2 - 你好组件
import { Component, Input, OnChanges, ChangeDetectionStrategy } from '@angular/core';
import { FormGroup } from '@angular/forms';
@Component({
selector: 'hello',
template: `<form [formGroup]="form">
<app-input [form]="form"></app-input>
</form>`,
styles: [``],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class HelloComponent implements OnChanges {
@Input() form: FormGroup;
ngOnChanges(changes) {
console.log(changes)
}
}
3 - 输入组件
import { Component, Input, OnInit, OnChanges, ChangeDetectionStrategy } from '@angular/core';
import { FormGroup } from '@angular/forms';
@Component({
selector: 'app-input',
template: `Name : <input type="text" [formControl]="nameFormcontrol" /> {{nameFormcontrol.value}} <br /><br />
Age : <input type="text" [formControl]="ageFormcontrol" /> {{ageFormcontrol.value}}`,
styles: [``],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class InputComponent implements OnInit, OnChanges {
@Input() form: FormGroup;
nameFormcontrol;
ageFormcontrol;
ngOnInit() {
this.nameFormcontrol = this.form.get('name');
this.ageFormcontrol = this.form.get('age');
}
ngOnChanges(changes) {
console.log(changes)
}
}
在 hello 组件和 input 组件中,我都将 changedetection 策略设置为 onpush。正如您在上面看到的,我正在应用程序组件中创建一个表单组实例并将其传递给子组件。现在,当我单击应用程序组件上的按钮更改表单值时,它会更改输入字段中的值,但不会更改纯文本。它仅在我从两个子组件中删除推送更改检测时才有效。即使表单组值发生变化,也不会调用 ngOnChanges。
是不是很奇怪。更改检测如何用于输入而不是此处的纯文本?
有人可以解释一下吗?在不删除 onpush 更改检测的情况下,它的解决方法是什么。
解决方案
尽管我不确定这是否是理想的解决方案,但我找到了解决此问题的方法。
我们可以监听表单组值的变化,然后在输入组件中触发变化检测
this.form.valueChanges.subscribe( () => {
this.cdr.detectChanges()
});
这样,它会连同输入一起更新标签值。
这是解决方案:
https://stackblitz.com/edit/angular-change-detection-form-group-value-change-issue-resolved
我不确定这是否是 Angular 的错误,但很高兴我找到了一些解决方法:)
推荐阅读
- java - 存储的变量总是读为假?
- javascript - 为什么我的简单对等应用程序无法在服务器上运行
- android - 这个图标叫什么(反应原生矢量图标)
- javascript - 为什么我没有看到我的智能合约进入区块链?
- typescript - 如何根据现有对象值定义 Typescript 对象类型?
- c# - csvhelper 从行中的不同项目映射字段
- c# - 在 PictureBox 上捕获 KeyDown 事件
- javascript - 如何在 JavaScript 中返回嵌套对象的属性
- docker - 如何使用 Docker 公开一系列 UDP 端口
- python - Matplotlib 在所有子图上绘制相同的点