角度表单验证:比较不同表单组中的两个字段

如果这是某个问题的副本,我很抱歉.我找不到解决问题的方法.

任何人都可以解释或举例说明如何比较一种形式但不同形式组的两个字段吗?

下面是代码片段,了解我的表单和验证器的外观:

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将由Angular调用,而不是由你调用.因此它无法访问Component.

所以你必须绑定它.

您可以在FormGroup上使用get方法来获取group1的字段值:(< FormGroup> this.mainForm.get(‘group1’)).get(‘field’).value

尝试一下:

组件类:

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

模板:

<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>

这是你的参考Sample StackBlitz.

点赞