在 Angular 中识别子窗体中控件的值更改

Identify value changes from a control in sub form in Angular

我有如下的组件层次结构。

componentA.ts如下

  this.componentAForm= this.formBuilder.group({
  componentBForm: this.formBuilder.group({
    componentCForm: this.formBuilder.group({
      control1: new FormControl(''),
      control2: new FormControl('')
    }),

ComponentA.html如下

<componentB [formGroup]="componentAForm.controls.componentBForm"></componentB>

ComponentB.ts如下

 this.componentBForm= this.controlContainer.control as FormGroup;

componentB.html如下

<componentC [formGroup]="componentBForm.controls.componentCForm"></componentC>

现在我的问题是我需要访问 componentB 中 formGroupC 中的 valuechanges 并在其中做一些事情。同时,当我访问组件 A 中的 formGroupA 时,应该可以访问所有已更改的(formGroup 层次结构的当前值)。我怎样才能实现。

您已经拥有 HTML

中的代码

在组件B中,可以这样写

componentBForm.controls.componentCForm.valueChanges.subscribe((data) => { whatever });

在您的组件中实施 ControlValueAccessor。所以那些将成为自定义控件。

https://angular.io/api/forms/ControlValueAccessor

我尝试做的是,在 componentB 的 ngOnInit() 内,我为 formGroupC 创建了一个 tempFormGroup,值更改如下。

   ngOnInit(){
    this.componentBForm= this.controlContainer.control as FormGroup;
    this.tempcomponentCForm= this.componentBForm.controls.componentCForm as FormGroup;
    this.tempcomponentCForm.controls.control1.valueChanges.subscribe({
    this.tempcomponentCForm= this.componentBForm.controls.componentCForm as FormGroup;//this will allow the future changes //Whatever I want to do
      });

    }

但是在componentB.html

<componentC [formGroup]="omponentBForm.controls.componentCForm"></componentC >

目前看来可行。有人请提出针对此问题的最佳实践和可能的挑战