How to Validate FormArray length in angular2

后端 未结 6 1625
猫巷女王i
猫巷女王i 2021-02-02 09:16

I have a data driven form in angular2 like below

this.formBuilder.group({
  \'name\': [\'\',Validators.required],
  \'description\': [\'\', Validators.required],         


        
6条回答
  •  Happy的楠姐
    2021-02-02 09:52

    Add this custom validator to your validation service:

    minLengthArray(min: number) {
        return (c: AbstractControl): {[key: string]: any} => {
            if (c.value.length >= min)
                return null;
    
            return { 'minLengthArray': {valid: false }};
        }
    }
    

    And then when creating the form do the following:

    this.formBuilder.group({
      'name': ['',Validators.required],
      'description': ['', Validators.required],
      'places': this.formBuilder.array([], this.validationService.minLengthArray(1)) 
    });
    

    And you can check errors against the FormArray by checking FormArray.hasError('minLengthArray')

提交回复
热议问题