• angular6中formGroup嵌套formArray


    【前提】

    本项目中使用的框架:angular6 + ng-zorro-antd 1.8.x;

    要想在表单中使用formGroup,必须先引入ReactiveFormsModule,否则会报错;

    在app.module.ts中引入的同时还需在最近的module.ts文件中引入(看百度只需在app.module.ts中引入即可,但是在本项目中不生效)。

    import { FormsModule, ReactiveFormsModule } from '@angular/forms';
    @NgModule({
      imports: [FormsModule, ReactiveFormsModule],
      exports: [],
      declarations: [],
      providers: [],
    })
    

     【正文】

    formBuilder、formControl、formGroup及formArray的用法自行百度吧,下面直接贴代码:

    html:

    <form nz-form [formGroup]="validateForm" (ngSubmit)="submitForm()">
          <div class="process-item">
            <label>日期</label>
            <div>
              <nz-form-item>
                <nz-form-control>
                  <nz-date-picker formControlName="startTime" nzPlaceHolder="开始日期"></nz-date-picker>
                  <div nz-form-explain class="error" *ngIf="validateForm.controls.startTime.dirty&&validateForm.controls.startTime.hasError('required')">开始日期不能为空</div>
                </nz-form-control>
              </nz-form-item>
              <span></span>
              <nz-form-item>
                <nz-form-control>
                  <nz-date-picker formControlName="endTime" nzPlaceHolder="结束日期"></nz-date-picker>
                  <div nz-form-explain class="error" *ngIf="validateForm.controls.endTime.dirty&&validateForm.controls.endTime.hasError('required')">结束日期不能为空</div>
                </nz-form-control>
              </nz-form-item>
            </div>
          </div>
          <div class="process-item">
            <label>组合</label>
            <div formArrayName="testArr">
              <div><span class="add-btn" (click)="addItem()"><i class="icon-cmbnt icon-add"></i>添加</span></div>
              <div *ngFor="let item of testArrFormArray.controls;let i = index;" [formGroupName]="i">
                <nz-form-item>
                  <nz-form-control>
                    <nz-select style="100%" formControlName="etcName" nzAllowClear nzPlaceHolder="请选择场次">
                      <nz-option *ngFor="let option of testArrCopy" [nzLabel]="option" [nzValue]="option"></nz-option>
                    </nz-select>
                    <div nz-form-explain class="error" *ngIf="item.controls['etcName'].dirty&&item.controls['etcName'].hasError('required')">场次不能为空</div>
                  </nz-form-control>
                </nz-form-item>
                <span></span>
                <nz-form-item>
                  <nz-form-control>
                    <nz-date-picker nzFormat="MM-dd" formControlName="date" nzPlaceHolder="结束日期"></nz-date-picker>
                    <div nz-form-explain class="error" *ngIf="item.controls['date'].dirty&&item.controls['date'].hasError('required')">结束日期不能为空</div>
                  </nz-form-control>
                </nz-form-item>
                <i *ngIf="i>0" (click)="delItem(i)" class="icon-cmbnt icon-del"></i>
              </div>
            </div>
          </div>
          <nz-form-item class="footer-btn">
            <nz-form-control nz-col>
              <button nz-button nzType="primary" class="mr-14">提交</button>
              <button nz-button nzType="primary-empty" (click)="resetForm($event)">重置</button>
            </nz-form-control>
          </nz-form-item>
        </form>


     ts:

    import { Component, OnInit, ViewChild, Pipe, PipeTransform } from '@angular/core';
    import { FormBuilder, FormGroup, Validators, FormControl, FormArray } from '@angular/forms';
    
    @Component({
      selector: 'app-tesst,
      templateUrl: './test.component.html',
      styleUrls: ['./test.component.scss']
    })
    
    export class TestComponent implements OnInit {
        validateForm: FormGroup;
        testArryCopy = [];
        constructor(private fb: FormBuilder, private route: ActivatedRoute) {
            this.validateForm = this.fb.group({
                startTime: [null, [Validators.required]],
                endTime: [null, [Validators.required]],
                testArr: this.fb.array([
                    new FormGroup({
                        etcName: new FormControl(null, Validators.required),
                        date: new FormControl(null, Validators.required)
                    })
                ])
            });
        }
        //需要将testArr的属性实例成一个FormArray
        get testArrFormArray() {
            return this.validateForm.controls['testArr'] as FormArray;
        }
    
        creatRow() {
            return this.fb.group({
               etcName: [null, [Validators.required]],
               date: [null, [Validators.required]]
            });
        }
    
        //新增组合
        addItem(){
            this.testArrFormArray.push(this.creatRow());
        }
        //刪除组合
        delItem(i) {
            this.testArrFormArray.removeAt(i);
        }
       //提交表单
        submitForm() {
            Object.keys(this.validateForm.controls).map(i => {
                if (i) {
                    this.validateForm.controls[i].markAsDirty();
                    this.validateForm.controls[i].updateValueAndValidity();
                }
            });
            this.testArrFormArray.controls.forEach(v => {
                Object.keys(v['controls']).map(key => {
                    if (v['controls'][key]) {
                        v['controls'][key].markAsDirty();
                        v['controls'][key].updateValueAndValidity();
                    }
                });
            });
            if (this.validateForm.valid) {
              ...
            }
        }
        //重置表单
        resetForm(e: MouseEvent): void {
            e.preventDefault();
            this.clearForm();
        }
        clearForm() {
            this.validateForm.reset();
            for (const key in this.validateForm.controls) {
              this.validateForm.controls[key].markAsPristine();
              this.validateForm.controls[key].updateValueAndValidity();
            }
            this.bishiArrFormArray.controls.forEach(v => {
                Object.keys(v['controls']).map(key => {
                   if (v['controls'][key]) {
                       v['controls'][key].markAsPristine();
                       v['controls'][key].updateValueAndValidity();
                   }
                });
            });
        }
    }

     鄙人不才,欢迎补充。

  • 相关阅读:
    Android RecyclerView如何去掉上拉刷新和下拉加载的阴影
    python如何在列表、对象、集合中根据条件筛选数据
    解决Glide在一个imageview上更换图片时会闪的问题
    响应时间三个非常重要的时间点
    android 向系统日历添加日程事件
    android 系统日历 插入重复事件规则 RRULE
    android Calendar Provider
    android edittext设置获取焦点
    android 自定义光标颜色
    android动态改变TextView字体大小遇到的问题
  • 原文地址:https://www.cnblogs.com/myyouzi/p/14481221.html
Copyright © 2020-2023  润新知