How to Validate FormArray length in angular2

后端 未结 6 1549
猫巷女王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条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-02 10:05

    Validators.required does the magic for you:

    // using required 
    
    this.formGroup = this.formBuilder.group({
        taskTreeId: [Common.UID()],
        executionProgrammedTime: ["", [Validators.required]],
        description: [""],
        tasks: this.formBuilder.array([], Validators.required)
    });  
    
    // using custom validation
    
    export const minLengthArray = (min: number) => {
      return (c: AbstractControl): {[key: string]: any} => {
        if (c.value.length >= min)
          return null;
    
        return { MinLengthArray: true};
      }
    }
    
     this.formGroup = this.formBuilder.group({
            taskTreeId: [Common.UID()],
            executionProgrammedTime: ["", [Validators.required]],
            description: [""],
            tasks: this.formBuilder.array([], minLengthArray(2))
        });
    
    
    

提交回复
热议问题