Search code examples
typescriptangular6angular-reactive-formsformarray

How to add validation to FormArray onSubmit() in angular 6


I have gone through all the answers in stackOverflow and internet.

I have got solution only for FormArray with FormGroup, but i want save the data in FormArray only

WorkId:["a","b","c"]

and the data that i get from server also in the above format

and this is my Code

WorkIDList: this.formBuilder.array([
  this.formBuilder.control(""), Validators.required
], Validators.required);

get WorkIDlist() {
  return this.registerForm.get("WorkIDList") as FormArray;
}
addworkidlist() {
  this.WorkIDlist.push(this.formBuilder.control(""));
}
submit(data, event: Event) {
  this.submitted = true;
  if (this.registerForm.invalid) {
    this.validateAllFields(this.registerForm);
    return;
    // alert("all fields must be filled");
  } else {
    event.preventDefault();
    console.log("data", data);
  }
}
// validation on submit

validateAllFields(formGroup: FormGroup) {
  Object.keys(formGroup.controls).forEach(field => {
    const control = formGroup.get(field);
    if (control instanceof FormArray) {
      control.markAsTouched();
    }
    if (control instanceof FormControl) {
      control.markAsTouched({
        onlySelf: true
      });
    } else if (control instanceof FormGroup) {
      this.validateAllFields(control);
    }
  });
}
<div class="form-group">
  <div class="col-sm-9" formArrayName="WorkIDList">
    <div *ngFor="let address of WorkIDlist.controls; let i=index">
      <input class="form-control workIdList" type="text" [formControlName]="i" required />
      <!-- <div *ngIf="address.invalid && (address[i].dirty || address[i].touched)"
                    class="alert alert-danger">
                    <div *ngIf="address[i].errors.required">
                      WorkspaceName is required.
                    </div>
                  </div> -->
      <div *ngIf="address[i].invalid">
        <div *ngIf="address.hasError('required')">
          Error
        </div>
      </div>
    </div>
    <button type="button" (click)="addworkidlist()">Add</button>
  </div>
</div>

I can't give validation in html and can't throw error validation on submit() through script

Can anyone help on this issue.

Thanks in advance.


Solution

  • I found the solution to validate in HTML and typescript

    validateAllFields(formGroup: FormGroup) {
      Object.keys(formGroup.controls).forEach(field => {
        const control = formGroup.get(field);
        if (control instanceof FormArray) {
          for (const control1 of control.controls) {
            if (control1 instanceof FormControl) {
              control1.markAsTouched({
                onlySelf: true
              });
            }
            if (control1 instanceof FormGroup) {
              this.validateAllFields(control1);
            }
          }
          // control.markAsTouched();
        }
        if (control instanceof FormControl) {
          control.markAsTouched({
            onlySelf: true
          });
        } else if (control instanceof FormGroup) {
          this.validateAllFields(control);
        }
      });
    }
    <div class="form-group">
      <div class="col-sm-9" formArrayName="WorkIDList">
        <div *ngFor="let address of WorkIDlist.controls; let i=index">
          <input class="form-control workIdList" type="text" [formControlName]="i" required />
          <div *ngIf="address.invalid && (address.dirty || address.touched)" class="alert alert-danger">
            <div *ngIf="address.hasError('required')">
              WorkspaceName is required
            </div>
          </div>
        </div>
        <button type="button" (click)="addworkidlist()">Add</button>
      </div>
    </div>