Angular 2:将验证器添加到ngModelGroup [英] Angular 2: Add validators to ngModelGroup

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

问题描述

我正在使用ngModelGroup指令将多个表单输入分组在一起.

I am using a ngModelGroup directive to group several form inputs together.

在文档中( https://angular .io/docs/ts/latest/api/forms/index/NgModelGroup-directive.html ),我读到有一个validators: any[]属性.

In the docs (https://angular.io/docs/ts/latest/api/forms/index/NgModelGroup-directive.html) I read that there is a validators: any[] property.

这是否意味着我可以添加一个仅验证ngModelGroup的自定义验证器功能?如果可以,该如何使用?

Does this mean I can add a custom validator function which validates only that ngModelGroup ? If so, how do I use it?

那太好了,因为我想检查是否至少选中了ngModelGroup中的一个复选框.我不能使用required,因为这意味着需要 all 所有复选框.我在文档中找不到关于此的任何信息,或者我在错误的位置找东西?

That would be awesome because I would like to check if at least one of the checkboxes in the ngModelGroup is checked. I can't use required because that would mean all checkboxes are required. I can't find anything about this in the documentation or am I looking in the wrong place?

推荐答案

使用ngModelGroup和用于验证的自定义指令完全可以做到这一点.理解为何有效的关键是ngModelGroup

This is entirely possible with a ngModelGroup and a custom directive for validation. Key to understanding why this works is that ngModelGroup

创建FormGroup实例并将其绑定到DOM元素.

Creates and binds a FormGroup instance to a DOM element.

首先,我们将构建指令,该指令是非常简单的样板,没有什么特别的事情发生:

First, we'll build out our directive which is pretty boilerplate with nothing special going on:

@Directive({
  selector: '[hasRequiredCheckboxInGroup]',
  providers: [{provide: NG_VALIDATORS, useExisting: HasRequiredCheckBoxInGroup, multi: true}]
})
export class HasRequiredCheckBoxInGroup implements Validator, OnChanges {
  private valFn = Validators.nullValidator;

  constructor() {
    this.valFn = validateRequiredCheckboxInGroup();
  }

  validate(control: AbstractControl): {[key: string]: any} {
    return this.valFn(control);
  }
}

我们的验证功能是我们获取ngModelGroup创建FormGroup并将其应用的关键知识的地方:

Our validation function is where we take our key knowledge that ngModelGroup creates a FormGroup and apply it:

function validateRequiredCheckboxInGroup() : ValidatorFn {
      return (group) => { //take the group we declare in the template as a parameter
        let isValid = false; //default to invalid for this case
        if(group) {
          for(let ctrl in group.controls) {
            if(group.controls[ctrl].value && typeof group.controls[ctrl].value === 'boolean') { // including a radio button set might blow this up, but hey, let's be careful with the directives
              isValid = group.controls[ctrl].value;
            }
          }
        }

        if(isValid) {
          return null;
        } else {
          return { checkboxRequired: true };
        }
      }
    }

最后,在指令中包含并声明了指令之后,我们返回模板(需要使用表格):

And finally, having included and declared in our Module the directive, we return to the template (needs to be in a form):

<form #f="ngForm">
      <div ngModelGroup="checkboxes" #chks="ngModelGroup" hasRequiredCheckboxInGroup>
          <input type="checkbox" name="chk1" [(ngModel)]="checks['1']"/>
          <input type="checkbox" name="chk2" [(ngModel)]="checks['2']"/>
      </div>
      <div>
      {{chks.valid}}
      </div>
</form>

这是一个可与所有这些东西一起玩的小矮人: http://plnkr.co/edit/AXWGn5XwRo60fkqGBU3V?p=preview

And here's a plunker with all this available to play with: http://plnkr.co/edit/AXWGn5XwRo60fkqGBU3V?p=preview

这篇关于Angular 2:将验证器添加到ngModelGroup的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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