Angular Reactive Form - Apply validators only on specific field of object

535 Views Asked by At

I have a reactive form with a form array in it. When I init my form, I push some form controls with default values in my form array.

Here's the code:

formValues?.tipsAndTricks?.forEach((tipAndTrick) => {
  this.tipsAndTricks.push(
    this.fb.control(
      { id: tipAndTrick.id, tip: tipAndTrick.tip },
      { validators: [Validators.required, Validators.minLength(25), Validators.maxLength(2000)], updateOn: 'change' }
    )
  )
})

The problem is that my validators are not working because they are applied to an object:

{ id: tipAndTrick.id, tip: tipAndTrick.tip }

My question is how can I apply these validators only on the tip field of this object?

1

There are 1 best solutions below

5
Yong Shun On BEST ANSWER

Your FormArray contains objects, thus you should push FormGroup with this.fb.group() instead of FormControl.

While you can add the validator(s) to the field with:

{ tip: ['value', [/* Validators */]] }

or

{ tip: this.fb.control('value', [/* Validators */]) }

The complete code should be:

formValues?.tipsAndTricks?.forEach((tipAndTrick) => {
  this.tipsAndTricks.push(
    this.fb.group(
      { 
        id: [tipAndTrick.id], 
        tip: [tipAndTrick.tip, [
          Validators.required, 
          Validators.minLength(25), 
          Validators.maxLength(2000)]
        ] 
      }
    )
  )
})