验证项目数量

时间:2019-07-03 22:58:45

标签: angular

我正在尝试验证“引用”数组中的项目数量,该怎么办? 我想验证用户是否告知至少一个城市。 我正在尝试使用“ FormArray”验证,但无济于事

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 个答案:

答案 0 :(得分:0)

如果您需要数组具有至少1个成员,则只需向其添加Validator.required。

引用:新的FormArray(this.usuario.cites,[Validators.required])