问题
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;
};
}
回答1:
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.
来源:https://stackoverflow.com/questions/53426241/angular-form-validation-compare-two-fields-in-different-form-groups