如何使用表单生成器验证具有动态值的表单数组

How to validate form array with dynamic values using form builder

我正在做 angular 项目,我需要提交一个表格,其中包含考试

的一些值

当我单击添加按钮时动态创建表单字段,每一行 () 都将添加到表单中。

用于添加每个考试值。我也可以删除表格中的每一行。

要求是我需要为单击提交按钮时创建的每个动态行显示主题、标记和考试的验证消息(如果选中 invalid/not)。 exams 字段是一个多复选框列表,如果未选中任何内容,则进行验证

<form [formGroup] = "SettingsForm" (ngSubmit) = "SettingsFormSubmit()">
    <div class="row">
      <div class="col-xl-4">
        <input type="text" placeholder="Name" formControlName="Name">
      </div>
    <div class="row">
      <div class="col-xl-4 ">
        <p *ngIf="submitted && SettingsForm.get('Name').invalid class="text-danger">
          Name is required.
        </p>
      </div>
    </div>
    <div class="row">
      <div class="col-xl-12">
        <table class="table" formArrayName="PersonalData">
          <thead>
            <tr>
              <th>Subject</th>
              <th>Mark</th>
              <th>Exams</th>
              <th>Delete</th>
              <th><button type="button"  (click)="addPersonalData()" class="btn-blank">Add</button></th>
            </tr>
          </thead>
          <tbody>
            <tr [hidden]="!data.value.active"   *ngFor="let data of PersonalData().controls;let i=index" [formGroupName]="i">
              <td>
                <select class="form-control" formControlName="subject"  >
                  <option>Select Subject</option>
                  <ng-container *ngFor="let subject of subjects">
                  <option  value="{{ subject.id }}" >{{ subject.subject_name }}</option>
                  </ng-container>
                </select>
                <ng-container *ngIf="data.get(subject).invalid">
                  <span class="">error message</span>
                </ng-container>
              </td>
              <td>
                <select class="form-control" formControlName="mark">   
                  <option>Select Mark</option>
                  <option>50</option>
                  <option>60</option>
                  <option>90</option>
                </select>
                <ng-container *ngIf="data.get(mark).invalid">
                  <span class="">error message</span>
                </ng-container>
              </td>
              <td>
                <mat-form-field>
                  <mat-label>Select Exams</mat-label>
                  <mat-select  #examsSelect multiple formControlName="exams" >
                    <mat-option (click)="examsSelect()" *ngFor="let term of terms" [value]="term.id">
                      {{term.name}}
                    </mat-option>
                  </mat-select>
                </mat-form-field>
                  <ng-container *ngIf="data.get(exams).invalid">
                  <span class="">error message</span>
                </ng-container>
              </td>
              <td><button type="button"  (click)="deletedata(i)" >Delete</button>
              </td>
              <td><button type="button"  (click)="addPersonalData()" >Add</button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
    <div class="modal-footer">
      <button type="submit" class="btn btn-success">Submit</button>
    </div>
   </form> 



   this.SettingsForm = this.formBuilder.group({
    id: [''], 
    Name: ['',Validators.required],
    PersonalData: this.formBuilder.array([this.formBuilder.control('', Validators.required)])
   });


  PersonalData() : FormArray {
    return this.SettingsForm.get("PersonalData") as FormArray
  }

  newPersonalData(): FormGroup {
    return this.formBuilder.group({
      id: '',
      subject: '',
      mark: '',
     exams: '',
   })
  }

  addPersonalData() {
    this.PersonalData().push(this.newPersonalData());
  }

我正在将每个 PersonalData 动态保存到表单构建器中,所以一次假设如果我添加了 3 行,那么一组 3 个表单字段将成为它们的 as formarray 具有相同的 formcontrolname 如何验证和显示所有的错误消息动态生成的表单字段?我这样做时出错了..

`ERROR TypeError: Cannot read properties of null (reading 'invalid')`

您可以调用您的 formControlName.errors 直接在您的 html 中检查是否有错误,就像这样 *ngIf="name.errors?.required" (对于 Validators.required 的情况)。然后您可以显示一条消息,例如:“需要此值”。

它也可以在 component.ts 中调用以在发送数据之前验证表单。

享受编码吧!

表单初始化为

this.SettingsForm = this.formBuilder.group({
  id: [null],
  Name: [null, Validators.required],
  PersonalData: this.formBuilder.array([]),
});

为每个动态字段添加验证

  newPersonalData(): FormGroup {
    return this.formBuilder.group({
      id: '',
      subject: [null, Validators.required],
      mark: [null, Validators.required],
      exams: [null, Validators.required],
    });
  }

没有名称为 active 的字段,所以对其进行了评论

// [hidden]="!data.value.active"
<tr
*ngFor="let data of PersonalData().controls; let i = index"
[formGroupName]="i"
>

验证以逗号编码的控件名称

<ng-container *ngIf="data.get('subject').invalid">

Sample Demo