Search code examples
angularbindngforformarray

bind an array of data to form array in angular


I have a form where i used form array. In getstudentsArray i'm getting data of students. I want to display this dynamic data in formarray using ngfor. Please help me bind the getstudentsArray array in html form array Can you please fix my issue. Thanks in advance.

HTML

<span formArrayName="times">
<a (click)="addGroup()">Add New Textfield</a>
<span  *ngFor="let time of timesArray.controls; let i = index;">
  <span [formGroupName]="i">                         
    <input type="text" class="form-control" formControlName="lists" placeholder="enter dropdown options">  
  </span>
</span>
</span>
getstudentsArray: any = [];

getStudentDetails(){
  const obj: any = {
    ID: this.stu_id
  }
  this.service.postmethod('studentsDetails', obj).subscribe((res: any) => {
    this.respon= res;
    this.getstudentsArray = this.respon.test;
  });
}
{
    "test": [
        {"id": 1,"class": 5,"name": "john"},
        {"id": 2,"class": 5,"name": "tim"},
        {"id": 3,"class": 5,"name": "alex"},   
    ]
}

Solution

  • Here is your working solution : https://stackblitz.com/edit/angular-xeuupi

    First you need to create formgroup of object and then you need to push those groups on array. I have also added validator function if you want to add.

    For validators you can say :

    this.validators = {
       'name': Validators.compose([Validators.required, Validators.maxLength(50)])
    };
    

    And you need to pass this.validator instead of blank object {} in createFormGroup(...) method.