代码之家  ›  专栏  ›  技术社区  ›  Maryannah

反应形式:数组属性转换为对象

  •  3
  • Maryannah  · 技术社区  · 6 年前

    这个问题可以从 this stackblitz :

    我有一个有效载荷:

    payload = {
      id: 1,
      name: 'This is the payload',
      children: [
        { id: 1, name: 'Child 1' }
      ],
    };
    

    我用它创建了一个表单组:

    this.form = this.fb.group(this.payload);
    

    然后显示表单的值:

    {{ form?.value | json }}
    

    结果是:

    { "id": 1, "name": "This is the payload", "children": { "id": 1, "name": "Child 1" } }
    

    如你所见, children 属性从数组变为对象。

    1. 怎么会这样?
    2. 有没有可能阻止Angular这样做?
    3. 如果我需要使用formarray,有没有办法让它自动运行?
    1 回复  |  直到 6 年前
        1
  •  4
  •   ibenjelloun    6 年前

    您应该声明一个数组数组,因为group将数组作为参数[值,…验证器]:

    payload = {
        id: 1,
        name: 'This is the payload',
        children: [[
          { id: 1, name: 'Child 1' },
        ]],
      };
    

    根据 angular.io :

    this.fb.group({
       anArray: [[]]
    });
    
    // OR
    this.fb.group({
       anArray: this.fb.array([])
    });
    
    // OR
    this.fb.group({
       anArray: new FormControl([])
    });
    

    如果您想制作动态表单,请查看 this angular.io page .