How to Validate FormArray length in angular2

后端 未结 6 1550
猫巷女王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 09:51

    because you using wrong validator function name: minlength -> minLength

    demo code:

    import { Component, OnInit } from '@angular/core';
    import { FormBuilder, FormGroup, FormArray, Validators } from '@angular/forms';
    
    @Component({
      selector: 'app-root',
      template: `
        
    Places {{i + 1}}

    Status: {{ tpForm.valid }}

    `, styles: [ ` ` ] }) export class AppComponent implements OnInit { tpForm: FormGroup; constructor(private fb: FormBuilder) {} ngOnInit() { this.tpForm = this.fb.group({ 'name': ['',Validators.required], 'description': ['', Validators.required], 'places': this.fb.array([ this.fb.control('') ], Validators.minLength(1)) }) } get places(): FormArray { return this.tpForm.get('places') as FormArray; } onSubmit() { } addPlace() { this.places.push(this.fb.control('')); } removePlace(index) { this.places.removeAt(index); } }

    Plunker: https://plnkr.co/edit/cfi7nN?p=preview

提交回复
热议问题