我正在使用Angular 2,我试图在一个方法中调用它,但我收到一个错误:Cannot read property 'dataService' of undefined
passwordMatchValidator(g: FormGroup) {
console.log(this.dataService);
return g.get('password').value === g.get('repeat').value ? null : {'mismatch': true};
}
当我可以在它运行的方法之外的this.dataService时,这是因为现在是FormGroup吗?如果是这样,我将如何在此方法中调用this.dataService?
import { DataService } from '../../services/data.service';
@Component({
selector: 'app-register',
templateUrl: './register.component.html',
styles: []
})
export class RegisterComponent{
constructor(private fb: FormBuilder,
private locationService: LocationService,
private dataService: DataService){}
buildForm(): void {
this.step1Form = this.fb.group({
username: new FormControl('', {
validators: [Validators.required,
Validators.minLength(4)],
}),
email: new FormControl('', {
validators: [Validators.required,
Validators.pattern("^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$")],
}),
password: new FormControl('', {
validators: [Validators.required,
Validators.minLength(8)],
}),
repeat: new FormControl('', {
validators: [Validators.required,
Validators.minLength(8)],
}),
}, { validator: this.passwordMatchValidator });
}
passwordMatchValidator(g: FormGroup) {
console.log(this.dataService);
return g.get('password').value === g.get('repeat').value ? null : {'mismatch': true};
}
}
将验证器分配给控件时,必须保存上下文,例如:
fb.group({
password: [null, this.passwordMatchValidator.bind(this)]
})