【发布时间】:2017-03-10 04:45:57
【问题描述】:
我正在尝试使用 Reactive Forms 模块在 Angular 2 中构建一个注册表单。因此,我为表单定义了一个 FormGroup,然后我可以为其中的每个 FormControl 列出验证器。
考虑这个部分类:
export class TestFormComponent implements OnInit {
form: FormGroup;
password = new FormControl("", [Validators.required]);
passwordConfirm = new FormControl("", [Validators.required, this.validatePasswordConfirmation]);
constructor(private fb: FormBuilder) {
}
ngOnInit() {
this.form = this.fb.group({
"password": this.password,
"passwordConfirm": this.passwordConfirm
});
}
validatePasswordConfirmation(fc: FormControl) {
var pw2 = fc.value;
var pw = // how do I get this value properly????
if (pw === '') {
return {err:"Password is blank"};
}
if (pw2 === '') {
return {err:"Confirmation password is blank"};
}
if (pw !== pw2) {
return {err:"Passwords do not match"}
}
return null;
}
}
您可以看到我为passwordConfirm 字段创建了一个验证器,但我不知道如何获取主password 字段的值(用作验证器中的pw)来执行比较。
我不能只引用this.form.value.password,因为验证器中的this 不引用包含表单的主类。
有什么想法吗?
【问题讨论】:
标签: angular typescript angular2-forms