本文介绍了角反应形式阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need reactive form which result will be like this

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

I tried some codes but something wrong.

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

推荐答案

Givi,您有一个包含一个元素的数组,该数组内部有一个具有属性"account"的对象,该对象是另一个具有属性"accountNum"的对象字符串

Givi, you has an array with one element, inside the array an object with a propertie "account" that is another object with a propertie "accountNum" that is a string

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.请尝试理解,而不是简单地复制并粘贴答案.

You see that if you has an array you need a FormArray, if you need an object, you need a FormGroup and if you need a value, you need a FormControl. Please, try understand, not simply copy and paste the answer.

已更新显示一个.html来更改表单

Updated show a .html to change the form

好吧,您可以使用唯一的formControl

Well, you can use a unique formControl

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

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

But we are going to learn how manage a formArray. Normally if a formArray is a propertie of a formGroup we use some like

<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,因此我们可以做出类似的

If we can manage an array we need know that a formArray is a formGroup, so we can make some like

   <!--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>

这篇关于角反应形式阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 02:09