【问题标题】:angular reactive form array角反应形式阵列
【发布时间】:2019-06-16 21:51:05
【问题描述】:

我需要反应形式,结果会是这样的

我尝试了一些代码但有问题。

[{"account":{ "accountNum": "numbers which user will type in input" }}]

【问题讨论】:

标签: angular angular-reactive-forms


【解决方案1】:

Givi,你有一个包含一个元素的数组,在数组内有一个具有属性“account”的对象,该对象是另一个具有属性“accountNum”的对象,它是一个字符串

myForm=new FormArray([       //an formArray with one element
    new FormGroup({          //that is a formGroup with a propertie "account"
      account:new FormGroup({//that is a formGroup with a propertie "accountNum"
                             //    that is a FormControl
        accountNum:new FormControl("numbers which user will type in input") 
      })
    })
  ])

在.html中也看到了

<pre>{{myForm?.value|json}}</pre>

你会看到,如果你有一个数组,你需要一个 FormArray,如果你需要一个对象,你需要一个 FormGroup,如果你需要一个值,你需要一个 FormControl。请尝试理解,而不是简单地复制和粘贴答案。

更新显示一个.html来改变表格

好吧,你可以使用一个独特的formControl

<input [formControl]="myForm.at(0).get('account').get('accountNum')">

但是我们将学习如何管理一个formArray。通常,如果 formArray 是 formGroup 的属性,我们会使用类似

<form [formGroup]="myForm">
   <div formArrayName="myArray">
      <div *ngFor="let controls in myForm.get('myArray').controls;
               let i=index">
            <div [formGroupName]="i">
               <!--here the controls of our array-->
            </div>
      </div>
   </div>
</form>

如果我们可以管理一个数组,我们需要知道一个formArray是一个formGroup,所以我们可以做一些类似

   <!--see that we used [formGroup]-->
   <div [formGroup]="myArray"> 
      <div *ngFor="let controls in myArray.controls;
               let i=index">
            <!--see how replace the [formGroupName]="i" by [formGroup]="controls"
                      the variable of the *ngFor -->
            <div [formGroup]="controls">
            <!--here the controls of our array-->
            </div>
      </div>
   </div>

【讨论】:

  • 我是这样写的,它可以工作 pastebin.com/raw/2Lu1Twwi 有什么问题吗?
  • 如果您有多个文件(或者如果您的 formArray 可以存储多个唯一元素),请使用我在答案中指出的代码。在stackblitz.com/edit/angular-ubckvt?file=src/app/… 中查看您的示例。重要的是你要明白两种方式(你的和我的)都是一样的。您可以使用 formName="..." 或 [formControl]="myform.get('...')
  • formGroup(或formArray)的存在与我们是否有输入无关。输入可以使用多种方式获取/设置表单控件的值
猜你喜欢
  • 1970-01-01
  • 2019-06-04
  • 2020-05-20
  • 2021-07-24
  • 2018-07-30
  • 2020-04-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多