Angular 4数组验证 [英] Angular 4 array validation

查看:240
本文介绍了Angular 4数组验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要反应形式formArray验证方面的帮助.我想验证数组中的每个项目,但我不知道该怎么做.谢谢.

I need help with formArray validation in reactive form. I want validate each item in array, but i have no idea how can i do that. Thanks.

html代码:

    <label for="name">name:</label>
    <input formControlName="name" id="name" type="text">
    <div *ngIf="name.invalid && (name.dirty || name.touched)">
       <div *ngIf="name.errors.required">
         required
       </div>
    </div>

TypeScript代码:

 createForm() {
    this.form = this.fb.group({
      person: this.fb.array([this.initItemRows()])
    });
  }

initItemRows() {
    return this.fb.group({
      name: [''],
      info: ['']
    });
  }

  addNewRow() {
    const control = <FormArray>this.form.controls['person'];
    control.push(this.initItemRows());
  }

  deleteRow(index: number) {
    const control = <FormArray>this.form.controls['person'];
    control.removeAt(index);
  }

  get name() { return this.form.get('person.name'); }
  get info() { return this.form.get('person.info'); }

我尝试过:

initItemRows() {
    return this.fb.group({
      name: ['', Validators.required ],
      info: ['', Validators.required ]
    });
  }

它不起作用..

推荐答案

您的nameinfo的获取器实际上并不针对特定的表单控件,因为您的person是formArray,例如在您的表单中不存在.您需要做的是对每个表单组使用迭代,并使用该控件的组作为目标,因此您的模板应如下所示:

Your getters for name and info actually don't target the specific form controls, since your person is a formArray, for example this.form.get('person.name'); does not exist in your form. What you need to do, is use the iteration for each formgroup and target that group with its controls, so your template should look like this:

<div *ngFor="let p of form.controls.person.controls; let i = index" 
             [formGroupName]="i">
  <label for="name">name:</label>
  <input formControlName="name" id="name" type="text">
  <!-- check if the name in this group has the error -->
  <div *ngIf="p.controls.name.dirty">
    <div *ngIf="p.hasError('required', 'name')">Required</div>  
  </div>
</div>

演示

DEMO

进一步的建议是,您可以稍微缩短代码长度,并删除初始化/添加表单组到数​​组中并不需要的方法,因此在这里我删除了addNewRow,可以将initItemRows称为当您要添加新行时.

Furthermore a suggestion is, that you can shorten your code a bit and remove a method that isn't really needed for initializing/adding formgroup to your array, so here I removed the addNewRow, initItemRows can be called when you want a new row added.

this.form = this.fb.group({
  person: this.fb.array([])
});
this.initItemRows();

initItemRows() {
  let ctrl = <FormArray>this.form.controls.person;
  ctrl.push(this.fb.group({
    name: ['', Validators.required],
    info: ['', Validators.required]      
  }))
}

这篇关于Angular 4数组验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆