很抱歉,如果它与某人的问题重复。我没有找到解决问题的方法。
有人可以解释或举一个例子,说明如何比较一种形式但不同形式组中的两个字段吗?
下面是代码段,以查看我的表单和验证器的外观:
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;
};
}
答案 0 :(得分:1)
matchValidator
将由Angular而不是您调用。因此,它将无权访问组件的this
。
所以您必须绑定到它。
您可以在get
上使用FormGroup
方法来获取group1
的{{1}}的值:field
尝试一下:
组件类:
(<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');
}
}
这是您推荐的Sample StackBlitz。