Home > Mobile >  Angular - How to set validation based on a FormArray
Angular - How to set validation based on a FormArray

Time:10-24

I am currently building a website in angular, I'm facing a problem that I cant solve the validation of list of items admin need to key in requirements or update current ones that fetch from Api i try to implement angular reactive form array validation by this way but it doesn't work also it makes the first field has no content

  requirements: this.formBuilder.array([
    new FormControl('',Validators.required)
  ])

everything works fine and I can get the data and show it in the fields as well as to add new fields or delete one. now I want to validate if one of these fields is empty then to show warning message under this field and once the admin key in then this warning message to disappear

Thanks in advance

enter image description here

targetStudentForm:FormGroup;
constructor(
  private formBuilder:FormBuilder,
  ) {
  this.targetStudentForm = this.formBuilder.group({
    requirements: this.formBuilder.array([])
  }); 
}

get requirements(): FormArray {
  return this.targetStudentForm.controls.requirements as FormArray;
  }

  addReqItem(){
    this.requirements.push(new FormControl(""));
    }

for (let index = 0; index < this.course.learns.length; index  ) {
  this.requirements.push(new FormControl(this.course.learns[index]));
}

 if (this.course.learns.length==0) {
  this.requirements.push(new FormControl(""));
 }


  targetStudentSubmit(){
    this.isSubmitted = true;
    if (this.form.invalid) return;
    console.log(this.targetStudentForm);
}

And here the template

    <div formArrayName="requirements" *ngFor="let requirement of requirements.controls; let i = index">
          <input
            type="text"
            
            [formControlName]="i"
          />
          <small *ngIf="targetStudentForm.invalid" 
          
         >This field is required</small>
        </div>

CodePudding user response:

When you push new FormControl to FormArray, you have to do it to formArray.controls. And you have to set validator to the new FormControl.

addReqItem(){
  this.requirements.controls.push(new FormControl('',Validators.required));
}

for (let index = 0; index < this.course.learns.length; index  ) {
  this.requirements.controls.push(new FormControl(this.course.learns[index], Validators.required);
}

if (this.course.learns.length==0) {
  this.requirements.controls.push(new FormControl("", Validators.required));
}
  • Related