我使用Angular 4.0.0进行自定义组验证时遇到问题此表单组始终显示null {{modelform.get('passwords') . json}}
组件
import { Component, OnInit } from '@angular/core';
import { AbstractControl, FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
@Component({
templateUrl: './mdf-costomvalidation.component.html'
})
export class MDFCustomValidationComponent implements OnInit {
modelform: FormGroup;
constructor(private _formBuilder: FormBuilder) { }
ngOnInit() {
this.modelform = this._formBuilder.group({
firstname: ['', Validators.required],
lastname: ['', Validators.required],
passwords: this._formBuilder.group({
firstpass: ['', Validators.required],
secondpass: ['', Validators.required]
}, { Validator: this.passwordMatch })
});
}
passwordMatch(c: AbstractControl) {
return c.get('firstpass').value === c.get('secondpass').value ? null : {'nomatch': true};
}
modelformsubmit() {
console.log(this.modelform.value);
}
}
我试图在类之外声明passwordMatch()函数,并根据Angular.io API FormGroup示例将第二个参数称为'passwordMatch'而不是'this'关键字,但对返回值没有影响 .
function passwordMatch(c: AbstractControl) {
return c.get('firstpass').value === c.get('secondpass').value ? null : {'nomatch': true};
}
passwords: this._formBuilder.group({
firstpass: ['', Validators.required],
secondpass: ['', Validators.required]
}, passwordMatch)