将验证器中的字段与angular2进行比较

Ets*_*tse 3 typescript angular

我正在尝试在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};
    }
}
Run Code Online (Sandbox Code Playgroud)

Ets*_*tse 5

所以我通过将customValidator绑定到我的类的这个上下文来解决问题,如Sergio的评论中所解释的那样.

请记住,.bind(this)函数返回带有bound-context的函数的新实例.

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};
    }
}
Run Code Online (Sandbox Code Playgroud)