0

I'm trying to validate the amount of items in the 'cites' array, how could I do this? I would like to validate that the user informs at least one city. I'm trying to use 'FormArray' validations, but to no avail

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormArray, FormControl, Validators } from '@angular/forms';

@Component({
  selector: 'app-validacao2',
  templateUrl: './validacao2.component.html',
  styleUrls: ['./validacao2.component.css']
})
export class Validacao2Component implements OnInit {
  // tslint:disable-next-line:max-line-length
  usuario: any = {nome: '', email: '', cites: [new FormControl('São Paulo', [Validators.required])]};

  form = new FormGroup({
    nome: new FormControl(this.usuario.nome, [Validators.required, Validators.minLength(4)]),
    email: new FormControl(this.usuario.email, [Validators.required, Validators.email]),
    cites: new FormArray(this.usuario.cites, [Validators.min(1)])
  });

  constructor() { }

  get cites(): FormArray {
    return this.form.get('cites') as FormArray;
  }

  adicionarCidade() {
    this.cites.push(new FormControl('', [Validators.required]));
  }

  removerCidade(indice: number): void {
    this.cites.removeAt(indice);
  }

   onSubmit() {
     console.log(this.form.value);
   }

  ngOnInit() { }
}

1 Answers1

0

If you need your array to have atleast 1 member, then you can just add Validator.required to it.

cites: new FormArray(this.usuario.cites, [Validators.required])

Qellson
  • 532
  • 2
  • 7