0

I am working in angular 4 and facing an issue, I have created an array in form and bind each and every group with input field but when I fill the first field then it will automatically fill the second filed in browser but in form only value on one field will be available.

dynamicArray.ts

addNewArrayForm : FormGroup;

constructor(private formBuilder : FormBuilder){}

ngOnInit() {
   this.addNewArrayForm = this.formBuilder.group({
      testArray : this.formBuilder.array([])
   });

   let arrayValue = [1, 2, 3, 4, 5];
   let testArrayField = <FormArray>this.addNewArrayForm.controls['testArray'];
   for(let value of arrayValue){
      testArrayField.push(new FormControl(null));
   }

   checkValue(){
      console.log(this.addNewArrayForm.value);
      //Output 
      {
         testArray : ['1','12',null,null,null]
      }
   }
}

dynamicArray.html

<form [formGroup] = "addNewArrayForm">
   <div class="card" formArrayName="testArray" *ngIf="addNewArrayForm.controls['testArray'].value && (addNewArrayForm.controls['testArray'].value).length > 0">
      <div *ngFor="let value of addNewArrayForm.controls['testArray'].value; let x = index ">
         <input type="text" formControlName="{{x}}">
      </div>
      <div>
         <button type="button" class="btn" (click)="checkValue()">Click</button>
      </div>
   </div>
</form>

You can check my issue on this link: https://angular-pdx2q2.stackblitz.io

Thank you.

1 Answer 1

1

Simply use trackBy option on your ngFor directive to avoid the mess:

template

*ngFor="let value of addNewArrayForm.controls['testArray'].value; ...; trackBy: trackByFn"

component

trackByFn(index: number) {
  return index;
}

Forked Stackblitz Example

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.