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

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

问题描述

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

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

这是否意味着我可以添加一个自定义验证器函数来仅验证 ngModelGroup ?如果是这样,我该如何使用它?

那太棒了,因为我想检查是否至少选中了 ngModelGroup 中的一个复选框.我不能使用 required 因为这意味着 all 复选框是必需的.我在文档中找不到任何关于此的内容,还是我找错了地方?

解决方案

这完全可以通过 ngModelGroup 和用于验证的自定义指令实现.理解为什么这有效的关键是 ngModelGroup

<块引用>

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

首先,我们将构建我们的指令,该指令非常样板,没有什么特别之处:

@Directive({选择器:'[hasRequiredCheckboxInGroup]',提供者:[{provide: NG_VALIDATORS, useExisting: HasRequiredCheckBoxInGroup, multi: true}]})导出类 HasRequiredCheckBoxInGroup 实现 Validator、OnChanges {私人 valFn = Validators.nullValidator;构造函数(){this.valFn = validateRequiredCheckboxInGroup();}验证(控制:AbstractControl):{[键:字符串]:任何} {返回 this.valFn(control);}}

我们的验证函数是我们获取关键知识的地方,ngModelGroup 创建一个 FormGroup 并应用它:

function validateRequiredCheckboxInGroup() : ValidatorFn {返回(组)=>{//以我们在模板中声明的组作为参数让 isValid = false;//在这种情况下默认为无效如果(组){for(让 ctrl 在 group.controls 中){if(group.controls[ctrl].value && typeof group.controls[ctrl].value === 'boolean') {//包含单选按钮集可能会炸毁它,但是嘿,让我们小心指令isValid = group.controls[ctrl].value;}}}如果(有效){返回空;} 别的 {返回 { checkboxRequired: true };}}}

最后,在我们的模块中包含并声明了指令,我们返回到模板(需要在一个表单中):

<div ngModelGroup="checkboxes" #chks="ngModelGroup" hasRequiredCheckboxInGroup><input type="checkbox" name="chk1" [(ngModel)]="checks['1']"/><input type="checkbox" name="chk2" [(ngModel)]="checks['2']"/>

<div>{{chks.valid}}

</表单>

这里有一个 plunker 可以玩所有这些:http://plnkr.co/edit/AXWGn5XwRo60fkqGBU3V?p=preview

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

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

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

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?

解决方案

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

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);
  }
}

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>

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天全站免登陆