angular FormArray用法指南

angular表單的三大基本構(gòu)造塊
1.FormControl:?jiǎn)蝹€(gè)獨(dú)立的表單控件;
2.FormGroup:一組FormControl實(shí)例;
3.FormArray:控件數(shù)組,控件可為FormControl、FormGroup、FormArray的實(shí)例;

FormBuilder: 根據(jù)用戶指定的配置創(chuàng)建 abstractControl,FormBuilder 提供的語(yǔ)法糖可快速實(shí)例化 FormControl、FormGroupFormArray。

  • this.formBuilder.control() ;
  • this.formBuilder.group();
  • this.formBuilder.array()

FormArray 的使用場(chǎng)景:需要循環(huán)遍歷的表格,實(shí)現(xiàn)動(dòng)態(tài)增加或刪除表數(shù)據(jù)
常用方法

  • at($index); 獲取數(shù)組中位于index處的控件
  • push(); 數(shù)組末尾插入新的控件
  • removeAt($index) ; 移除數(shù)組中位于index處的控件
  • patchValue(); 賦值

DEMO1

this.userModel = this.formBuilder.group({
  name: ['', Validator.compose(...)],
  detailInfoModel: ['', this.formBuilder.array([this.initDetailInfo()])],
})

// 初始化FormArray detailInfo
initDetailInfoModel() {
  return this.formBuilder.group({
      phone: [''],
      salary: [0],
      extraMony: [0],
      TotalCount: []
  })
}

get detailInfoModel() {
    return this.userModel.get('detailInfoModel') as FormArray;
}

// 將獲取的詳情數(shù)據(jù)循環(huán)賦給表單組detailInfoModel
this.detailInfo = [{phone: 11, salary:11,...},{...}];
this.detailInfo.map((item,index) => {
    this.detailInfoModel.at(index).patchValue({
       phone: item.phone,
       salary: Number(item.salary),
       extraMony: Number(item.extraMony),
       TotalCount: item.TotalCount
  })
})

html表格中如果有合計(jì)需要?jiǎng)討B(tài)計(jì)算,可在合計(jì)中使用ngModel綁定需要累加的控件值

<form [formGroup]="userModel">
<table>
          <thead>
              <tr>
                  <th>電話</th>
                  <th>薪水</th>
                  <th>額外薪水</th>
                  <th>合計(jì)</th>
              </tr>
          </thead>
          <tbody formArrayName="detailInfoModel">
            <ng-container *ngFor="let item of userModel.get('detailInfoModel').controls as FormArray; let i = index" [formGroupName]="i">
                <tr>
                  <td><input type="text" class="form-control" formControlName="phone"></td>
                  <td><input type="number" class="form-control" formControlName="salary"></td>
                  <td><input type="number" class="form-control" formControlName="extraMony"></td>
                  <td><input type="number" class="form-control" formControlName="TotalCount" 
                    [ngModel]="item.controls.salary.value + item.controls.extraMony.value">
                  </td>
                </tr>
            </ng-container>
          </tbody>
</table>
</form>

DEMO2

場(chǎng)景描述:在一個(gè) form 表單中,需要?jiǎng)討B(tài)添加或刪除某個(gè)表單集


formArrayGIF.gif
創(chuàng)建表單組
  /**
   * 創(chuàng)建表單
   */
  private createForm() {
    this.detailForm = this.fb.group({
      name: [''],
      exotic_details: this.fb.array([])
    });
    this.addFormArrayItem();

  }

  /**
   * 定義 formArray
   */
  private newFormArrayItem(): FormGroup {
    return this.fb.group({
      strike_price: [],
      strike_schedule_type: [],
      payout: []
    });
  }

  /**
   * 添加表單組項(xiàng)
   */
  public addFormArrayItem() {
    this.exoticDetails.push(this.newFormArrayItem());
  }

  /**
   * 刪除表單組項(xiàng)
   */
  public removeFormArrayItem(index) {
    this.exoticDetails.removeAt(index);
  }

  /**
   * 獲取 formArray 表單
   */
  get exoticDetails(): FormArray {
    return this.detailForm.get('exotic_details') as FormArray;
  }

  /**
   * formArray 賦值
   * @param value:與formArray對(duì)應(yīng)的數(shù)組 [{strike_price: '', payout: '', ...}, ...]
   */
  private setFormArrayValues(item) {
    this.exoticDetails.patchValue(item);
  }
頁(yè)面中使用
<form [formGroup]="detailForm " (ngSubmit)="onSubmit()">
  <p>
    <label for="name">Name </label>
    <input type="text" id="name" name="name" formControlName="name">
  </p>
  <div formArrayName="exotic_details">
    <div *ngFor="let item of exoticDetails.controls; let i=index">
      <div [formGroupName]="i">
        <input type="text" formControlName="payout">
        <button (click)="removeFormArrayItem(i)">delete</button>
      </div>
    </div>
  </div>
  <p>
    <button type="submit">Submit</button>
  </p>
</form>
<p>
  <button type="button" (click)="addFormArrayItem()">add</button>
</p>
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • ¥開(kāi)啟¥ 【iAPP實(shí)現(xiàn)進(jìn)入界面執(zhí)行逐一顯】 〖2017-08-25 15:22:14〗 《//首先開(kāi)一個(gè)線程,因...
    小菜c閱讀 7,322評(píng)論 0 17
  • 版本:Angular 5.0.0-alpha 表單是商業(yè)應(yīng)用的支柱,我們用它來(lái)執(zhí)行登錄、求助、下單、預(yù)訂機(jī)票、安排...
    soojade閱讀 1,346評(píng)論 0 1
  • HTML 5 HTML5概述 因特網(wǎng)上的信息是以網(wǎng)頁(yè)的形式展示給用戶的,因此網(wǎng)頁(yè)是網(wǎng)絡(luò)信息傳遞的載體。網(wǎng)頁(yè)文件是用...
    阿啊阿吖丁閱讀 4,942評(píng)論 0 0
  • 動(dòng)態(tài)表單(React Forms)是一種動(dòng)態(tài)構(gòu)建表單的技術(shù),用于解決有時(shí)候手動(dòng)編寫(xiě)和維護(hù)表單所需工作量和時(shí)間會(huì)過(guò)大...
    阿貍不歌閱讀 7,841評(píng)論 0 2
  • 由萬(wàn)通指控,駕著新能,地勝利,世名科技所想到的 強(qiáng)非強(qiáng),弱非弱,這就是節(jié)奏 主流資金為王: 駕著新能 和 實(shí)名科技...
    天涯別院閱讀 369評(píng)論 0 0

友情鏈接更多精彩內(nèi)容