角反应形式阵列

时间:2019-06-16 21:51:05

标签: angular angular-reactive-forms

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

我尝试了一些代码,但是出了点问题。

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

1 个答案:

答案 0 :(得分:2)

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>
相关问题