【发布时间】:2016-02-19 12:22:28
【问题描述】:
我正在尝试在 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};
}
}
【问题讨论】:
-
你试过
this.customValidator.bind(this)吗(我认为这是语法)。另一种方法可能是匿名函数:new Control('', () => {})(粗箭头有助于解决我所看到的上下文问题) -
@EricMartinez this.customValidator.bind(this) 非常适合我。干杯!
-
对我也很好。如果您将其添加为答案,我可以将其设置为已接受:)
-
@Etse,你能告诉你
this.customValidator.bind(this)如何工作的代码吗? -
仍然收到错误消息:异常:RegisterPage 实例化期间出错!
标签: typescript angular