1

i have an form array which i want to limit to only 5 input elements generated by user and my form has following definition

 createskillForm()
    {
      this.skillForm=this.formBuilder.group({
        skills:this.formBuilder.array([this.createskillFeild()],Validators.minLength(1),Validators.maxLength(5))
      });
    }

i have tried making changes with minlength but it is showing the following error in the console :- RROR in src/app/components/com-profile/com-profile.component.ts(47,89): error TS2345: Argument of type 'ValidatorFn' is not assignable to parameter of type 'AsyncValidatorFn | AsyncValidatorFn[]'. Type 'ValidatorFn' is not assignable to type 'AsyncValidatorFn'. Type 'ValidationErrors' is not assignable to type 'Promise | Observable'. Type 'ValidationErrors' is not assignable to type 'Observable'. Property '_isScalar' is missing in type 'ValidationErrors'. what i can do to limit adding user only five skills ?

2
  • is there a method creating each new form? if there is, you could start in it with if (this.myFormArray.controls.length >= 5) return; this example will vary with each particular case, but you get the idea. If this is a method, do tell me to add it as an answer! Hope it helps. Commented Apr 23, 2019 at 23:02
  • 2
    The 'space' character is your friend; not your enemy. Commented Apr 23, 2019 at 23:06

1 Answer 1

1

Wrap your validators in an array. The error you're getting is because maxLength isn't an async validator, which is the variable you're putting it into..

constructor(formState: any = null, validatorOrOpts?: ValidatorFn | >AbstractControlOptions | ValidatorFn[], asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[])

This is the correct code below. Not sure if this solves the problem you're trying to solve, but it fixes the error you have right now.

this.skillForm = this.formBuilder.group({
        skills:this.formBuilder.array([this.createskillFeild()], [ Validators.minLength(1), Validators.maxLength(5)] )
      });
Sign up to request clarification or add additional context in comments.

2 Comments

It is still adding more than 5 fields and i want user to be able to add 5 fields only
I thought it would still add more than 5 fields. I believe the length validator is for string or number length only. Add the Validators.required validator to the array and that should fix it. Otherwise it would need a custom validator (which is a really easy one to do in this case).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.