其他分享
首页 > 其他分享> > angular 动态添加、删除表单项

angular 动态添加、删除表单项

作者:互联网

一、嵌套表单动态添加删除

1. 静态表单嵌套

------- 使用了ng-zorro (https://ng.ant.design/docs/introduce/zh)

demo.component.html


<form [formGroup]="formGroup">

    <div>

        <label>名称: </label>

        <input type="text" formControlName="title" ([ngModel])="formData.title" />

        <nz-form-explain *ngIf="formGroup.get('title').dirty && formGroup.get('title').errors">请填写名称!</nz-form-explain>

    </div>

    <div formGroupName="user">

        <div>

            <label>用户名: </label>

            <input type="text" formControlName="config.userName" [(ngModel)]="formData.config.userName" />

            <nz-form-explain *ngIf="formGroup.get('user.userName').dirty && formGroup.get('user.userName').errors">请填写姓名!</nz-form-explain>

        </div>

        
        <div>

            <label>密码: </label>

            <input type="text" formControlName="config.userPwd" [(ngModel)]="formData.config.userPwd" />

            <nz-form-explain *ngIf="formGroup.get('user.userPwd').dirty && formGroup.get('user.userPwd').errors">请填写密码!</nz-form-explain>

        </div>

    </div>

</form>

demo.component.ts


private formGroup: FormGroup;

private fromData: {title = ''; user: {userName = ''; userPwd = ''}};



construct(private _fb: FormBuilder) {}



export class DemoComponent  implements OnInit {

   ngOnInit() {    // 自定义验证规则

    this.formGroup = this._fb.group({

        title: [null, [null, Validators.required]],

        user: this._fb.group({

            userName:[null, Validators.required],

            userPwd:[null, Validators.required],

       });

    });

  }



// 验证表单

validateForm() {

    for (const i in this.formGroup.controls) {
      form.controls[ i ].markAsDirty();
      form.controls[ i ].updateValueAndValidity();
    }
    // 验证是否通过
    if (form.valid) { // 验证通过
       //////////
    }

}



// 获取数据

getData() {

    const data = this.formData;

    console.log(data);

}


}


2. 动态表单嵌套

---- 数组式添加

1. demo.component.html


<form [formGroup]="formGroup">

<div formGroupName="sqxx">
    <button style="width:60%" (click)="addData($event)">

        <i nz-icon type="plus"></i>添加申请信息

    </button>
    <!--添加的课程量列表-->
    <nz-table
              *ngIf="applyInfoArray.length > 0"
              #sqxxTableData
              nzSize="middle"
              [nzData]="applyInfoArray"
              [nzShowPagination]="false"
              [nzSize]="'small'"
              class="kclsq-sqxx-table"
            >
        <thead>
                <tr>
                  <th>类型</th>
                  <th>数量</th>
                  <th>操作</th>
                </tr>
        </thead>
        <tbody>
              <ng-container *ngFor="let item of infoArray; index as i;">
                <tr>
                  <td><input nz-input placeholder="类型" [formControlName]="item.type" style="width: 120px;"></td>
                  <td><input nz-input placeholder="工作量" [formControlName]="item.num" style="width: 120px;"></td>
                  <td><a href="javascript:;" (click)="delInfo(item.type, sqxxItem.num)"><i nz-icon type="delete" theme="outline"></i></a> </td>
                </tr>
                <nz-form-explain *ngIf="(formGroup.value['sqxx'][item.type] === '' && isSqxxValid) || (formGroup.value['sqxx'][item.num] === ''&& isSqxxValid)">类型、数量均不能为空!</nz-form-explain>
              </ng-container>

        </tbody>
    </nz-table>
</div>
</form>

2. demo.component.ts


formGroup: FormGroup;

// 动态表单变量

 isSqxxValid = false;
 infoArray: any[] = [];



construct(private _fb: FormBuilder) {}



export class DemoComponent  implements OnInit {

    ngOnInit() {

    // 自定义验证规则

    this.formGroup = this._fb.group({

       sqxx: this._fb.group({});

    });

    // 默认添加一项

   this.addData();
   }



    // 点击添加表单项按钮

    addData() {

       // 获取唯一值
       const uid1 = this.getUID();
       const uid2 = this.getUID();
       // 申请信息数组添加数据
       this.infoArray.push({type: uid1,num: uid2});
       console.log(this.applyInfoArray);
       // 添加FormControl
       const control = <FormGroup>this.addFormGroup.controls['sqxx'];
       ////// 1. 创建FormControl
       const typeControl = new FormControl([null, Validators.required]);
       const numControl = new FormControl([null, Validators.required]);
       ///// 2. 设置默认值
       typeControl.setValue('');
       numControl.setValue('');
       //// 3. 添加FormControl至sqxx表单控件内
       control.addControl(uid1,typeControl);
       control.addControl(uid2,numControl);

    }

    // 生成唯一值

   getUID() {

       return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
          const r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
          return v.toString(16);
      });

   }

}



// 删除表单项

  delInfo(type, num) {
    if (this.infoArray.length > 1) {
      // 从申请信息记录数组中删除此项
      for (let i = 0; i < this.infoArray.length; i++) {
        if (this.infoArray[i].type===type && this.infoArray[i].num===num) {
          this.infoArray.splice(i, 1);
        }
      }
      const sqxxControl = <FormGroup>this.formGroup.controls['sqxx'];
      sqxxControl.removeControl(type);
      sqxxControl.removeControl(num);
    } else {
      this._msgService.warning('这已是最后一项,不可删除');
    }
  }



///////// 额外补充方法::::

// 最终获取数据

getData() {

       // 构造动态表单信息

      const formDataValue = this.formGroup.value;

      const sqxxData = [];
      for (let i = 0; i < this.infoArray.length; i++) {
        const item = {
          num : formDataValue.sqxx[this.infoArray[i].num],
          type: formDataValue.sqxx[this.infoArray[i].type]
        };
        sqxxData.push(sqxxItem);
      }
       console.log(sqxxData);

}



// 验证表单

validateForm() {

    this.isSqxxValid = true; // 保证和别的表单一同验证;

    for (const i in this.formGroup.controls) {
      form.controls[ i ].markAsDirty();
      form.controls[ i ].updateValueAndValidity();
    }
    // 验证是否通过
    if (form.valid) { // 验证通过
       //////////
    }

}


二、# 一、非嵌套表单动态添加删除。可参照 https://ng.ant.design/components/form/zh


FormGroup 和 FormArray的区别

标签:infoArray,const,controls,表单,添加,单项,formGroup,angular
来源: https://www.cnblogs.com/zero-zm/p/10421624.html