简体   繁体   中英

Angular Reactive Form - FormArray ChangeDection onPush not working

We are using ChangeDetectionStrategy Onpush in all the components, so we are following dump/smart component approach, so we are keeping all the logical part in service/facade side.

Right now we need to generate dynamic controls using Reactive Forms, FormGroup, FormArray,

So we are preparing FormGroup and FormArray in service side, and passing these to dump component as Input parameter, in this case I couldn't pass these as behaviour subject as observable, I'm directly passing as Input parameter.

If anything changes in FormArray, it doesn't not reflect in dump component due to the OnPush changeDectionStrategy.

I have mocked the implementation in this stackblitz

In this sample, I have prepared FormArray, FormGroup in service file, and passing to dump component via smart component.

I couldn't find proper samples on Behavioursubject and Abstract control,

If it is possible to pass FormArray, FormGroup as Observable, Kindly help me to know.

In the stackblitz example, both the FormGroup and FormArrays are undefined even from the Layer-Container Component because the variables are taken from the service before the initial data is loaded. If you do that, and then fetch the service variables and pass it to the child component, then the values will be obtained.

import { Component, OnInit, ChangeDetectionStrategy } from '@angular/core';
import { LayerService } from '../layer.service';

@Component({
  selector: 'app-layer-container',
  templateUrl: './layer-container.component.html',
  styleUrls: ['./layer-container.component.css'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class LayerContainerComponent implements OnInit {
layerFormGroup ;
layerFormArray ;

  constructor(private service : LayerService) { 
    this.service.loadInitialData();
    this.layerFormGroup = this.service.layerFormGroup;
    this.layerFormArray = this.service.layerFormArray; 
  }

  ngOnInit() {
    this.service.loadInitialData();
  }

}

And since both FormArray and FormGroup are not primitive data types, the @Input() cannot recognize the changes and we probably will not be able to detect the changes. Passing a new reference of these variables might just do the trick.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM