I'm following an online course in Angular2 and during a lesson that I was coding along with, I came across an error, but cannot figure out where I went wrong.
I tried to look at similar question around the web but couldn't find any valid solution. The closest I came was this answer, angular2 async form validation, but either the suggestions were irrelevant or it didn't work.
Here is my code:
Component
export class SignUpFormComponent {
form: ControlGroup;
constructor(fb: FormBuilder){
this.form = fb.group({
username: ['', Validators.compose([
Validators.required,
UsernameValidators.cannotContainSpace
]), UsernameValidators.shouldBeUnique],
password: ['', Validators.required]
});
}
signup(){
console.log(this.form.value);
}
}
Validators
export class UsernameValidators{
static shouldBeUnique(control: Control){
console.log("taken");
return new Promise((resolve, reject) => {
setTimeout(function(){
if(control.value == "example")
resolve({ shouldBeUnique: true });
else
resolve(null);
}, 1000);
});
}
static cannotContainSpace(control: Control){
if(control.value.indexOf(" ") >= 0){
return { cannotContainSpace: true };
}
return null;
}
}
Relevant parts of the form
<input
ngControl="username"
id="username"
type="text"
class="form-control"
#username="ngForm">
<div *ngIf="username.control.pending">Checking for uniqueness...</div>
<div
*ngIf="username.errors.shouldBeUnique"
class="alert alert-danger">
Username is already taken.
</div>
When I run a server locally and start typing into the form the div with the pending message does not appear, and if I type "example" into the input field the error message does not pop up. What am I missing? Thanks.
<input ngControl="username" id="username" type="text" class="form-control">*ngIf="username.errors.required", which works properly on the page.