我正在尝试在Angular2中创建具有“重复密码”功能的注册表。我希望使用自定义验证器作为表单控件来工作。
我遇到的问题是,当验证程序运行时,“ this-context”似乎已设置为验证程序,因此我无法访问RegistrationForm类上的任何本地方法。而且我似乎找不到从验证器访问ControlGroup的任何好方法。
有谁知道在自定义验证器中访问同一控件组中其他控件的好方法?
是该组件的简短示例:
import { Component, View } from 'angular2/angular2';
import { Validators, ControlGroup, Control, FORM_DIRECTIVES, FORM_BINDINGS } from 'angular2/angular2';
@Component({
selector: 'form-registration'
})
@View({
directives: [FORM_DIRECTIVES, ROUTER_DIRECTIVES],
template: `
<form (submit)="register($event)" [ng-form-model]="registerForm">
<label for="password1">Password:</label>
<input id="password1" ng-control="password1" type="password" placeholder="Passord" />
<label for="password2">Repeat password:</label>
<input id="password2" ng-control="password2" type="password" placeholder="Gjenta passord" />
<button class="knapp-submit" type="submit" [disabled]="!registerForm.valid">Registrer deg</button>
</form>
`
})
export class RegistrationForm {
registerForm: ControlGroup;
constructor() {
this.registerForm = new ControlGroup({
password1: new Control('', Validators.required),
password2: new Control('', this.customValidator)
});
}
public register(event: Event) {
// submit form
}
private customValidator(control: Control) {
// check if control is equal to the password1 control
return {isEqual: control.value === this.registerForm.controls['password1'].value};
}
}
因此,我通过将customValidator绑定到类的此上下文来解决该问题,如Sergio的评论中所述。
请记住,.bind(this)函数返回具有绑定上下文的新函数实例。
import { Component, View } from 'angular2/angular2';
import { Validators, ControlGroup, Control, FORM_DIRECTIVES, FORM_BINDINGS } from 'angular2/angular2';
@Component({
selector: 'form-registration'
})
@View({
directives: [FORM_DIRECTIVES, ROUTER_DIRECTIVES],
template: `...my form template...`
})
export class RegistrationForm {
registerForm: ControlGroup;
constructor() {
this.customValidator = this.customValidator.bind(this);
this.registerForm = new ControlGroup({
password1: new Control('', Validators.required),
password2: new Control('', this.customValidator)
});
}
public register(event: Event) {
// submit form
}
private customValidator(control: Control) {
// check if control is equal to the password1 control
return {isEqual: control.value === this.registerForm.controls['password1'].value};
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句