当我调用 get Api angular 8 时,我无法在 formArray 中动态创建 formArray [英] I am not able to create a formArray inside formArray dynamically when i call get Api angular 8

查看:16
本文介绍了当我调用 get Api angular 8 时,我无法在 formArray 中动态创建 formArray的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法在获取数据时动态创建表单控件.以及特别是 formControl 的值,如任务和模板名称.提前致谢.

I am not able to create dynamically form control when I get a data. and the value in particular formControl like task and template name . Thanks in advance.

{
  "items": [
    {
      "templatename": "Defult",
      "tasks": [
        "task-1",
        "task-2 ",
        "task-3",
      ]
    },
    {
      "templatename": "Eccormce",
      "tasks": [
        "task-1 ",
        "task-2",

      ]
    },
    {
      "templatename": "co-oprate",
      "tasks": [
        "task-1",
        "task-2",
        "task-3"
      ]
    }
  ]
}

推荐答案

我建议您迭代 json 值,然后创建不同的控件.

What I suggest you is to iterate over your json values and then create the different controls.

在初始化时,您可以创建第一个 FormArray,然后获取它并将 json 的所有 items 推入其中,最后对另一个执行相同的操作FormArray 代表你的任务

On your initialisation you can create the first FormArray, then you get it and push in it all the items of your json, and finally do the same for your other FormArray which represent your tasks

ngOnInit(){
  const items = this.json.items
  this.form = new FormGroup({
    items : new FormArray([])
  })
  let itemsForm = (<FormArray>this.form.get('items'))
  for (let i = 0; i < items.length; i++){
    itemsForm.push(this.initItem(items[i]))
  } 
}

initItem(item){
  let itemGroup = new FormGroup({
    templatename : new FormControl(item.templatename),
    tasks : new FormArray([])
  })
  let tasksItem = (<FormArray>itemGroup.get('tasks'))
  for (let i = 0; i < item.tasks.length; i++){
    tasksItem.push(new FormControl(item.tasks[i]))
  }
  return itemGroup;
}

当然,这是两次相同的迭代,只是 FormArray 和您放入其中的内容发生了变化,因此您可能可以将其分解为单个方法,但这里只是向您展示如何可以做嵌套的 FormArray

Of course this is two times the same iteration, just the FormArray and what you put in it change so you can factorize it in a single method probably, but here is just to show you how you can do nested FormArray

这里工作 stackblitz,您可以在其中测试示例

Here is a working stackblitz where you can test the example

这篇关于当我调用 get Api angular 8 时,我无法在 formArray 中动态创建 formArray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆