簡體   English   中英

如何使用 forms 在 angular9 模板中填充數組值

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

.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

{

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

}

如何在模板中填充數組元素? 使用這些代碼,我得到了 null 字段。 在檢查時我在輸入字段中獲取值,即使它顯示為空字段

關於 FormArrays 的簡要說明

如果我們想要一個 object 像

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

我們有一個 object 數組,所以我們需要一個 FormGroups (*) 的 FormArray。 要創建它,有一個返回 FormGroup(FormArray 的一個元素)的 function 很有用

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

如果我們的 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
    })
}

如果只想 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
}

現在我們要向數組中添加元素。 請記住,FormArray 的每個元素都是一個 FormGroup,但我們有一個 function 返回一個 formGroup!

所以,我們可以簡單地使用

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

如果我們想在數組中添加 formArray,我們通常將數組“映射”到 FormGroup 並創建數組,puff。 想象一下你有一個數據數組,你可以做

   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()))    

嗯,看in.html

首先檢查是否一切正常

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

我們正在使用輸入和 div

如果在 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>

如果 FormArray 是獨立的,則嚴格模式存在問題。 在我們可以使用之前

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

現在,我們創建一個輔助 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>

你可以在stackblitz中看到

更新了如何填充給定的數組數據

還記得我們寫this.formArray=new FormArray(this.data.map(x=>this.createGroup()))時候嗎?

寫什么呢

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

?

好吧,將函數 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),
       })
    }

結尾

(*) 如果我們只想管理數字數組或字符串數組,FormArray 可以是 FormControls 的 FormArray

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM