gpt4 book ai didi

angular - 表单组值更改时不会触发更改检测

转载 作者:太空狗 更新时间:2023-10-29 17:27:20 25 4
gpt4 key购买 nike

我创建了一个简单示例来演示我面临的一个奇怪问题。

堆栈 Blitz - 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。正如您在上面看到的,我在应用程序组件中创建了一个表单组实例并将其传递给子组件。现在,当我单击应用程序组件上的按钮来更改表单值时,它会更改输入字段中的值,但不会更改纯文本。仅当我从两个子组件中删除推送更改检测时它才有效。即使 formgroup 值发生变化,也不会调用 ngOnChanges。

enter image description here

是不是很奇怪。更改检测如何适用于输入而不适用于此处的纯文本?

有人可以给我解释一下吗?在不删除 onpush 变化检测的情况下,它的解决方法是什么。

最佳答案

虽然我不确定这是否是理想的解决方案,但我找到了解决此问题的方法。

我们可以监听表单组值的变化,然后在输入组件中触发变化检测

this.form.valueChanges.subscribe( () => {
this.cdr.detectChanges()
});

通过这种方式,它会连同输入一起更新标签值。

enter image description here

解决方法如下:

https://stackblitz.com/edit/angular-change-detection-form-group-value-change-issue-resolved

我不确定这是否是 Angular 的错误,但很高兴我找到了一些解决方法:)

关于angular - 表单组值更改时不会触发更改检测,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53640559/

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