Search code examples
htmlangularformarrayform-control

How to pass validators as required inside form array angular?


I need to make all the objects for skills as required. How can I achieve this?

this.feedbackForm = this.fb.group({
      applicantId: [''],
      comments: [''],
      recommendation: [''],
      skills: this.fb.array(
        this.skills.map((t) => {
          this.fb.control(t);
        })
      ),
    });

I need to make the skills as required for each object.


Solution

  • you can make the skills formArray as required, and then all the skills in it will be required like this:

    this.feedbackForm = this.fb.group({
      applicantId: [''],
      comments: [''],
      recommendation: [''],
      skills: this.fb.array(
        this.skills.map((t) => {
          this.fb.control(t);
        }), {validators: Validators.required}
      ),
    });
    

    or in formControl specific

     this.feedbackForm = this.fb.group({
      applicantId: [""],
      comments: [""],
      recommendation: [""],
      skills: this.fb.array(
        this.skills.map((t) => {
          this.fb.control(t, { validators: [Validators.required] });
        })
      ),
    });
    

    i suggest reading formBuilder documentation

    https://angular.io/guide/reactive-forms#creating-dynamic-forms