首页 > 解决方案 > 表单组值更改时不会触发更改检测

问题描述

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

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 更改检测的情况下,它的解决方法是什么。

标签: angularangular-changedetection

解决方案


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

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

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

这样,它会连同输入一起更新标签值。

在此处输入图像描述

这是解决方案:

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

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


推荐阅读