I am trying to create a registration form in Angular2, having a "repeat password" functionality. I want this to work using a custom validator as a form-control.
The problem I am having is that the "this-context" seems to be set to the validator when the validator is running so I cant access any local methods on the RegistrationForm class. And I can't seem to find any good way to access the ControlGroup from the validator.
Anyone know a good way to access other controls in the same control-group inside a custom validator?
The is a short sample of the component:
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};
}
}