简体   繁体   English

如何使用 forms 在 angular9 模板中填充数组值

[英]How to populate Array values in angular9 template using forms

.html page .html页面

<pre>
<div *ngFor="let data of data;let i=index" class="row_wrap">
<div class="row_inner_wrap">
<div class="row">
<div class="col-md-12">
<div class="col-md-5 inner_row">
<mat-form-field appearance="outline" class="input-container">
<input  (click)="readonly($event)" formControlName="status" matInput [value]="data?.employeeStatus" class="form-control" placeholder="{{ 'Status'| translate }}" readonly>
</mat-form-field>
<i class="fa fa-check edit_dept" data-uuid="" data-type="department"></i>
</div>
<div class="col-md-6 inner_row b4_del_header">
<mat-form-field appearance="outline" class="input-container">
<input matInput placeholder="{{ 'description'| translate }}" formControlName="description" (click)="readonly($event)"  [value]=" data?.description" class="form-control" readonly>
</mat-form-field>
<div class="add_des_edit">
<div class="update_icon">
<i class="fa fa-check edit_dept" data-uuid="" data-type="department"></i>
</div>
</div>
</div>
<div *ngIf="!enableEdit" class="del_icon" (click)="ondelete(data?._id)">
<i class="fa fa-trash-o del del_department" aria-hidden="true" style="visibility: visible;" data-uuid=""></i>
</div>
<div class="add_icon"  style="display: none"><i class="fa fa-plus add_row" data-uuid=""></i>
</div>
<div *ngIf="enableEdit" class="edit_icon" (click)="onUpdate()" style="display: inline-block;">
<i class="fa fa-check edit_row edit_row_department" data-uuid=""></i>
</div>
</div>
 </div>
 </div>
</div>

.component.ts .component.ts

{

  constructor(private fb: FormBuilder,
     private elRef: ElementRef,
     private settingservice: SettingsService) {
        this.emp_status = this.fb.group({
          status: [],
          description : []
     });
  }

}

How can I populate the array elements in my template?如何在模板中填充数组元素? With these codes, I'm getting null fields.使用这些代码,我得到了 null 字段。 while inspecting I'm getting values in the input field even though it showing empty field在检查时我在输入字段中获取值,即使它显示为空字段

a brief explain about FormArrays关于 FormArrays 的简要说明

If we want an object like如果我们想要一个 object 像

[
{status:'status 1',description:'description 1'},
{status:'status 2',description:'description 2'},
{status:'status 3',description:'description 3'},
   ...
]

We has an array of object, so we need a FormArray of FormGroups (*).我们有一个 object 数组,所以我们需要一个 FormGroups (*) 的 FormArray。 To create it's usefull has a function that return a FormGroup (one element of the FormArray)要创建它,有一个返回 FormGroup(FormArray 的一个元素)的 function 很有用

createGroup():FormGroup
{
   return new FormGroup({
      status:new FormControl(),
      description:new FormControl(),
   })
}

If our FormArray belongs to a FormGroup, it's usefull has a getter function that return our FormArray如果我们的 FormArray 属于 FormGroup,那么有一个 getter function 会返回我们的 FormArray

form:FormGroup; //<--declare the form
get statusArray():FormArray
{
    return this.form.get('emp_status') as FormArray
}
//in ngOnInit
ngOnInit()
{
    this.form=new FormGroup({
       other_property:new FormControl(),
       emp_status=new FormArray([]) //<--see that we create an empty FormArray
    })
}

If only want the FormArray itself only declare如果只想 FormArray 本身只声明

formArray:FormArray
//in ngOnInit we create the formArray empty -well you can do it in the declaration-
ngOnInit()
{
   this.formArray=new FormArray([]) //<--see that we create an empty FormArray
}

Now we are going to add elements to the array.现在我们要向数组中添加元素。 Remember that each element of the FormArray is a FormGroup, but we has a function that return a formGroup!请记住,FormArray 的每个元素都是一个 FormGroup,但我们有一个 function 返回一个 formGroup!

So, we can add simply using所以,我们可以简单地使用

this.statusArray.push(this.createGroup()) //if we are using a formArray inside a FormGroup
this.formArray.push(this.createGroup()) //if we has the formarray standalone

If we want add the formArray based in an array, we usually "map" the array to a FormGroup and create the array, puff.如果我们想在数组中添加 formArray,我们通常将数组“映射”到 FormGroup 并创建数组,puff。 Imagine you has an array of data, you can do想象一下你有一个数据数组,你可以做

   this.form=new FormGroup({
       other_property:new FormControl(),
       emp_status=new FormArray(
         this.data.map(x=>this.createGroup()) //<--each element of this data
                                              //like a formGroup
       )
    })

//or with our standalone FormArray
this.formArray=new FormArray(this.data.map(x=>this.createGroup()))    

Well, to see in.html嗯,看in.html

First check if it's all ok首先检查是否一切正常

<pre>
{{form?.value|json}}
</pre>
//or
<pre>
{{formArray.value|json}}
</pre>

we are using inputs and divs我们正在使用输入和 div

if is in a FormGroup如果在 FormGroup 中

<form [formGroup]="form">
   <!--say to Angular we are going to use the formArray using formArrayName-->
   <div formArrayName="emp_status">
       <!--iterate over the controls of formArray and use [formGroupName]-->
        <!--see that we use our getter function-->
     <div *ngFor="let group of statusArray.controls;let i=index" [formGroupName]="i">
          <!--use formControlName, we are yet in a formGroup-->
          <input formControlName="status">
          <input formControlName="description">
     </div>
   </div>
</form>

If the FormArray is standalone there are a problem with the strict mode.如果 FormArray 是独立的,则严格模式存在问题。 before we can use在我们可以使用之前

 /**BEFORE***/
 <div *ngFor="let group of formArray.controls;let i=index" [formGroup]="group">

Now, we create an auxiliar function现在,我们创建一个辅助 function

getGroupAt(index)
{
    return this.formArray.at(index) as FormGroup
}

<form [formGroup]="formArray">
     <!--iterate over the controls of formArray and use [formGroup]-->
     <div *ngFor="let group of formArray.controls;let i=index" [formGroup]="getGroupAt(i)">
          <!--use formControlName, we are yet in a formGroup-->
          <input formControlName="status">
          <input formControlName="description">
     </div>
   </div>
</form>

You can see in stackblitz你可以在stackblitz中看到

Updated how populate the array data given更新了如何填充给定的数组数据

Remember when we write this.formArray=new FormArray(this.data.map(x=>this.createGroup())) ?还记得我们写this.formArray=new FormArray(this.data.map(x=>this.createGroup()))时候吗?

What about write写什么呢

this.formArray=new FormArray(this.data.map(x=>this.createGroup(x))) 

? ?

Well, change the funciton createGroup for some like好吧,将函数 createGroup 更改为类似

createGroup(data:any=null):FormGroup
    {
       data=data || {status:null,description:null}
       return new FormGroup({
          status:new FormControl(data.status),
          description:new FormControl(data.description),
       })
    }

END结尾

(*) a FormArray can be a FormArray of FormControls if we want to manage only an array of numbers or an array of strings (*) 如果我们只想管理数字数组或字符串数组,FormArray 可以是 FormControls 的 FormArray

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM