首页 > 解决方案 > 反应形式正在验证列表中的所有迭代

问题描述

我在 *ngFor 中使用响应式表单在我的应用程序中进行验证。但是,当我尝试仅验证一次迭代时,表单将在所有迭代中进行验证。

我尝试使用模板驱动的表单,它运行良好。下面是模板驱动表单的工作代码

<div class="form-group col">
  <label>Flower License</label>
  <input type="text" name="fLicense" class="form-control" [(ngModel)]="f.fLicense" #fLicense="ngModel" [ngClass]="{ 'is-invalid': statusForm.submitted && fLicense.invalid }" required>
  <div *ngIf="statusForm.submitted && fLicense.invalid" class="invalid-feedback">
    <div *ngIf="fLicense.errors.required">flower License is required</div>
  </div>
</div>

对于反应式方法,以下是我的代码 HTML

<div *ngFor="let f of flowers">
  <div>{{f.type}} </div>
  <form [formGroup]="statusForm" (ngSubmit)="submitStatus()">
    <div class="form-group col-sm-4">
      <label>Flower License</label>
      <input class="form-control" type="text" formControlName="fLicense" [class.invalid]="!statusForm.controls['fLicense'].valid && statusForm.controls['fLicense'].touched ">
      <div *ngIf="!statusForm.controls['fLicense'].valid && (statusForm.controls['fLicense'].touched || isSubmitted)">
        <div class="invalid-feedback" style="display: block;">Please enter flower License Number</div>
      </div>
  </form>
  </div>
</div>

ts

ngOnInit() {
  this.statusForm = this.formBuilder.group({
    fLicense: ['', Validators.required],
  });
}

submitStatus(f) {
  this.isSubmitted = true;
  // stop here if form is invalid
  if (this.statusForm.invalid) {
    return;
  }
}

我尝试使用 来执行此操作FormArray,但我无法包含formControl在表单数组中。它抛出错误

  const newArray = new FormArray({
      this.statusForm = new FormGroup({
        hempLicense: new FormControl(['', Validators.required])
      })

    });

标签: angulartypescript

解决方案


由于您有值数组,因此您必须创建 FormArray 而不是 FormControl。

 this.statusForm = this.formBuilder.group({
      fLicense: this.formBuilder.array(this.createFLicenseArray(this.flowers))
 });

 createFLicenseArray(flowers) {
     return flowers.map(flower =>
      this.formBuilder.control("", [Validators.required]));
 }

然后循环 formArray 控件以显示单个 fLicense

<form [formGroup]="statusForm">
    <div class="form-group col-sm-4" formArrayName="fLicense" *ngFor="let flow of fLicenseArray.controls;let i = index">
        <label>Flower License</label>
        <input class="form-control" type="text" [formControlName]="i">
        <div *ngIf="!fLicenseArray.at(i).valid && (fLicenseArray.at(i).touched)">
            <div class="invalid-feedback" style="display: block;">Please enter flower License Number</div>
        </div>
    </div>
</form>

例子


推荐阅读