Angular框架专题

Angular框架中FormArray中嵌套FormGroup

2021-12-18  本文已影响0人  听书先生

Angular中FormGroup是用来管理一组表单控件的,响应式表单使用FormArray来动态的管理表单控件,FormArray是不能独立使用的,必须跟在FormGroup下面,否则会出现错误。

1、类文件代码:
   public form: FormGroup;
   
   //  构造函数中声明一个FormBuild对象
   constructor(private _fb: FormBuilder) { }

接着的工作便是初始化form表单:

  constructor(private _fb: FormBuilder) {
    this.form = this._fb.group({
      setting: this._fb.array([]),
    });
  }

这样就构建了一个嵌套了一个FormArray的FormFroup。
为了更便捷的获取到form中的setting项的数组,我们使用get方法来简化一下:

  get settingFormArray() {
    return this.form.controls['setting'] as FormArray;
  }
  ngOnInit(): void {
    this.settingFormArray.push(
      this._fb.group({
        height: 0,
        width: 0,
      })
    );
  }
this.addressFormArray.removAt(需要删除元素的下标)
import { Component, OnInit } from '@angular/core';
import { FormArray, FormBuilder, FormControl, FormGroup } from '@angular/forms';

@Component({
  selector: 'app-form',
  templateUrl: './form.component.html',
  styleUrls: ['./form.component.scss'],
})
export class FormComponent implements OnInit {
  public form: FormGroup;

  get settingFormArray() {
    return this.form.controls['setting'] as FormArray;
  }

  setting = {
    height: 0,
    width: 0,
  };

  Objectkeys = Object.keys;

  constructor(private _fb: FormBuilder) {
    this.form = this._fb.group({
      setting: this._fb.array([]),
    });
  }

  ngOnInit(): void {
    this.settingFormArray.push(
      this._fb.group({
        height: 0,
        width: 0,
      })
    );
  }

  delete(i: number) {
    this.settingFormArray.removeAt(i);
  }

  submitForm() {}
}

2、模板中使用

<form [formGroup]="form">
  <h3>默认设置项</h3>
  <div formArrayName="setting">
    <div *ngFor="let control of settingFormArray.controls; let i = index">
      <div [formControlName]="i">
        <div>
          <label>高度</label>
          <input nz-input placeholder="请输入高度" [(ngModel)]="setting['height']" formControlName="height" />
        </div>
        <div>
          <label>宽度</label>
          <input nz-input placeholder="请输入宽度" [(ngModel)]="setting['width']" formControlName="width" />
        </div>
        
      </div>
      <button nz-button nzType="primary" style="margin-top: 10px;" (click)="delete(i)">删除</button>
    </div>
  </div>
</form>

简单的测试用例.png
上一篇下一篇

猜你喜欢

热点阅读