首页 > 解决方案 > how to limit form array length?

问题描述

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 ?

标签: javascriptangulartypescript

解决方案


将您的验证器包装在一个数组中。您收到的错误是因为 maxLength 不是异步验证器,而是您将其放入的变量..

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

这是下面的正确代码。不确定这是否可以解决您要解决的问题,但它可以解决您现在遇到的错误。

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

推荐阅读