Angular reactive formarray returns first Index value as a null object

528 views Asked by At

In my Angular form while moving from one form to another the formControl can not rendering it's particular value instead it is displaying last visited form values.

Eg. If I have visited product_id = 1 and there the formControl('productValue') having values like 10, 11, 12. Now I am moving to product_id = 2 so at that time it should display product_id = 2 related values (45, 89, 63) but it renders the previously visited product_id = 1 values i.e 10, 11, 12

  import { Injectable } from "@angular/core";
  import { FormGroup, FormBuilder, FormControl, FormArray } from "@angular/forms";
  @Injectable({
    providedIn: "root",
  })
    
  export class ProductService {
    public productForm: FormGroup = this.fb.group({
      inventoryCollection: new FormArray([
        new FormGroup({ productStatus: new FormControl(""), productValue: new FormControl("") })
      ])
    });
    
    getInventoryData(productId) {
      let controlsCollection = <FormArray>this.productForm.get('dataCollection')
      this.getCollectionById(productId).subscribe((res: any) => {
        res.forEach(data => {
          controlsCollection.push(new FormGroup({
            productStatus: new FormControl(data.status)
            productValue: new FormControl(data.productValue)
          }))
        });
      })
    }
  }

Component in which calling getInventoryData() method

export class ProductComponent implements OnInit {
    constructure(private router: Router) {
        this.route.parent.params.subscribe(params => { 
            this.params = { id: Number(params['id']) }
  })}

    ngOnInit() { 
        this.productService.getInventoryData(this.params.id)
    }
}

HTML form is as below:

  <form [formGroup]="productService.productForm">
    <div formArrayName="dataCollection">
      <div [formGroupName]="i" *ngFor="let element of details; let i = index">
        <input matInput type="text" formControlName="productValue">
        <mat-select formControlName="productStatus" value="{{productService.details[i].productStatus === '0' ? 'Active' : 'Inactive'}}">
          <mat-option value="AC">Active</mat-option>
          <mat-option value="IA">Inactive</mat-option>
        </mat-select>
      </div>
    </div>
  </form>

P.S: I have visited product_id = 1" and "moving to product_id = 2" means is a router navigation.

 http://localhost:4500/product/1/collection i.e product_id = 1
 http://localhost:4500/product/2/collection i.e product_id = 2
0

There are 0 answers