【问题标题】:bind an array of data to form array in angular绑定数据数组以形成角度数组
【发布时间】:2021-05-16 00:46:57
【问题描述】:

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

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"},   
    ]
}

【问题讨论】:

  • 你有什么问题?
  • 感谢您的回复。如上所示,我在“getstudentsArray”中有数据。我想在 html formarray 中绑定它。当我使用 ngfor 绑定它时,我只得到一个,即使它有 3 个
  • 你创建formarray的方式不对。
  • 你能解释一下吗
  • stackblitz.com/edit/… 我做了一个关于我如何创建表单数组的堆栈闪电战。然后稍后解释我的绑定。

标签: angular bind ngfor formarray


【解决方案1】:

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

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

对于验证器,您可以说:

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

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

【讨论】:

  • 在这里,绑定后我们可以在哪里添加新的表单域,我应该也可以选择添加新的域。
  • 我已经用随机数据女士更新了 stackblitz 上的代码。您现在可以验证并根据您的需求和逻辑进行设置。
  • 如果将代码的一些相关部分发布在答案中会很好(除了 StackBlitz 链接)
猜你喜欢
  • 2015-03-25
  • 2020-06-06
  • 2021-02-08
  • 1970-01-01
  • 1970-01-01
  • 2018-07-31
  • 2019-03-31
  • 2019-08-18
  • 1970-01-01
相关资源
最近更新 更多