0
votes

in Angular Reactive forms - i have array like this 3 items :

productList = [{
  productId : "104",
  productName : computer
},
{
  productId : "105",
  productName : sprots
},
{
  productId : "106",
  productName : location
}]

declared form group like this :

this.productFormGroup = this.formBuilder.group({
      productFormArray: new FormArray([], CustomValidators.minNumberInputFieldRequired(1)),
    });

creating input fields like this :

productList.forEach((element) => {
        productFormArray.push(new FormControl('', [Validators.pattern(ValidationPatterns.required)]));
      });

bind like this :

<div *ngFor="let item of formControls; let i = index">
    <input type="text" [formControlName]="i" class="form-control">
</div>

Question :

how do i get 3 textbox updated value with their id on submit button?

Submit Button Event : -

if (this.productFormGroup.invalid) {
  return;
}
this.productFormGroup.value.productFormArray ? - it is return only update value, not Id.

there should be way to create text box with id while pushing item in form Array

1

1 Answers

0
votes

you have to create productId and productName field(FormControl) in the FormGroup. On User Interface side only bind productName field as textbox, because productId is used for your internal reference. See the below code Example : app.component.ts

import { Component,OnInit } from '@angular/core';
import { FormBuilder,FormGroup,FormArray } from '@angular/forms'


@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
  name = 'Angular';
  productList = [{
    productId : "104",
    productName : "computer"
  },
  {
    productId : "105",
    productName : "sprots"
  },
  {
    productId : "106",
    productName : "location"
  }];

  constructor(public formBuilder:FormBuilder){

  }

productFormGroup :FormArray
  ngOnInit() {
        this.productFormGroup = this.formBuilder.array([])
        this.productList.forEach(product=>{
              this.productFormGroup.push(this.formBuilder.group({
                productId:[product.productId],
                productName:[product.productName]
              }))
        })
  }

  onSubmit(){
  console.log(this.productFormGroup.value)
    
  }
}

On User Interface side, bind the productName on textbox field. see the below code example:

<div [formGroup]="product" *ngFor="let product of productFormGroup.controls">
    <input formControlName="productName" type="text" />
</div>
{{productFormGroup.value | json}}

I hope this will solve your problem. See the working code example on stackblitz