Angular 表单验证:比较不同表单组中的两个字段 [英] Angular form validation: compare two fields in different form groups

查看:25
本文介绍了Angular 表单验证:比较不同表单组中的两个字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果它与某人的问题重复,我很抱歉.我没有找到解决我的问题的方法.

谁能解释或举例说明如何比较一个表单中不同表单组中的两个字段?

以下是代码片段,用于查看我的表单和验证器的外观:

private createForm() {const testGroups = {groupOne: this.fb.group({fieldOne: this.fb.control(null)}),组二:this.fb.group({fieldTwo: this.fb.control(null, [this.matchValidator])})};this.testForm = this.fb.group(testGroups);}matchValidator(来自:FormControl):ValidatorFn {return (to: AbstractControl): { [key: string]: any } =>{返回 from.value &&to.value &&from.value === to.value?{ fieldMatch: true }: 空值;};}

解决方案

matchValidator 将由 Angular 调用,而不是由您调用.所以它不能访问组件的this.

所以你必须绑定它.

您可以在 FormGroup 上使用 get 方法来获取 group1field 的值: (this.mainForm.get('group1')).get('field').value

试试这个:

组件类:

import { Component } from '@angular/core';从@angular/forms"导入 { FormGroup, FormBuilder, FormControl, ValidatorFn, AbstractControl };@成分({选择器:'我的应用',templateUrl: './app.component.html',styleUrls: ['./app.component.css']})导出类 AppComponent {mainForm:FormGroup;构造函数(私人FB:FormBuilder){}ngOnInit() {this.mainForm = this.fb.group({group1: this.fb.group({场地: []}),group2: this.fb.group({字段:[null, [this.matchValidator.bind(this)]]})});}matchValidator(control: AbstractControl): { [key: string]: boolean } |空值 {const fromValue = control.value;如果(this.mainForm){const toValue = (<FormGroup>this.mainForm.get('group1')).get('field').value;if (fromValue && toValue && fromValue === toValue) {console.log('控制:', 控制);返回 { 'fieldMatch' : true };}console.log('控制:', 控制);返回空;}}获取 group2Field() {return (<FormGroup>this.mainForm.get('group2')).get('field');}}

模板:

<div formGroupName="group1"><label for="">组 1 字段</label><input type="text" formControlName="field">

<小时><div formGroupName="group2"><label for="">组 2 字段</label><input type="text" formControlName="field"><p *ngIf="group2Field?.errors?.fieldMatch">这些字段匹配</p>

</表单>

这是一个 示例 StackBlitz 供您参考.

I'm sorry if it's a duplicate of someone question. I didn't find a solution for my problem.

Can anybody explain or give an example how to compare two fields in one form but in different form groups?

Here is code snippet to see how my form and validator are look like:

private createForm() {

    const testGroups = {
        groupOne: this.fb.group({
            fieldOne: this.fb.control(null)
        }),
        groupsTwo: this.fb.group({
            fieldTwo: this.fb.control(null, [this.matchValidator])
        })
    };

    this.testForm = this.fb.group(testGroups);
}

 matchValidator(from: FormControl): ValidatorFn {
    return (to: AbstractControl): { [key: string]: any } => {
        return from.value && to.value && from.value === to.value
            ? { fieldMatch: true }
            : null;
    };
}

解决方案

matchValidator will be called by Angular and not by you. So it won't have the access to the Component's this.

So you will have to bind to it.

You can use the get method on a FormGroup to get the group1's field's value: (<FormGroup>this.mainForm.get('group1')).get('field').value

Give this a try:

Component Class:

import { Component } from '@angular/core';
import { FormGroup, FormBuilder, FormControl, ValidatorFn, AbstractControl } from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  mainForm: FormGroup;

  constructor(private fb: FormBuilder) { }

  ngOnInit() {
    this.mainForm = this.fb.group({
      group1: this.fb.group({
        field: []
      }),
      group2: this.fb.group({
        field: [null, [this.matchValidator.bind(this)]]
      })
    });

  }

  matchValidator(control: AbstractControl): { [key: string]: boolean } | null {
    const fromValue = control.value;
    if(this.mainForm) {
      const toValue = (<FormGroup>this.mainForm.get('group1')).get('field').value;
      if (fromValue && toValue && fromValue === toValue) {
        console.log('Control: ', control);
        return { 'fieldMatch' : true };
      }
      console.log('Control: ', control);
      return null;
    }
  }

  get group2Field() {
    return (<FormGroup>this.mainForm.get('group2')).get('field');
  }
}

Template:

<form [formGroup]="mainForm">
  <div formGroupName="group1">
    <label for="">Group 1 Field</label>
    <input type="text" formControlName="field">
  </div>
  <hr>
  <div formGroupName="group2">
    <label for="">Group 2 Field</label>
    <input type="text" formControlName="field">
    <p *ngIf="group2Field?.errors?.fieldMatch">These fields match</p>
  </div>
</form>

Here's a Sample StackBlitz for your ref.

这篇关于Angular 表单验证:比较不同表单组中的两个字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆