validation - Inject a service in a custom validator in Angular2 -
i try use service in custom validator check if username exists.
import {component} 'angular2/core'; import { control, controlgroup, formbuilder } "angular2/common"; import {characterservice} "./character-service"; @component({ selector: 'register-character-form', template: ` <h2 class="ui header">a new adventurer coming...</h2> <form (ngsubmit)="register()" [ngformmodel]="characterform" class="ui form"> <div class="field"> <label>nom</label> <input ngcontrol="name"> </div> <button type="submit" class="ui button">enter in adventure</button> </form> `, providers: [characterservice] }) export class registercharacterformcmp { characterform: controlgroup; name: control; constructor(private _characterservice: characterservice, fb: formbuilder) { this.name = fb.control('', this.characternamevalidator); this.characterform = fb.group({ name: this.name }); } register(): void { //todo: implement } // not works, binds control characternamevalidator(control: control) { return this._characterservice.ischaracternamealreadyexists(control.value) ? {namecharacteralreadyexistserror: true} : null; } } it doesn't work. in characternamevalidator, 'this' references control , not class. service undefined. how can use service in validator ?
more globally, how can pass arguments in custom validator ?
you need control this means in validation. can bind
this.name = fb.control('', this.characternamevalidator.bind(this)); everything else should work expected then.
Comments
Post a Comment