绑定数据数组以形成角度数组

问题描述

我有一个表单,其中使用了表单数组。 在getstudentsArray 中,我正在获取学生的数据。 我想使用 ngfor 在 formarray 中显示这个动态数据。 请帮我绑定html表单数组中的getstudentsArray数组 你能解决我的问题吗? 提前致谢。

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,"name": "tim"},{"id": 3,"name": "alex"},]
}

解决方法

这是您的工作解决方案: https://stackblitz.com/edit/angular-xeuupi

首先您需要创建对象的表单组,然后您需要将这些组推送到数组上。如果你想添加,我还添加了验证器功能。

对于验证器,您可以说:

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

并且您需要在 createFormGroup(...) 方法中传递 this.validator 而不是空白对象 {}。