I am learning promises and I am trying to get a simple example to work but I get the error. The promises role is just to check whether a certain name has been entered and produce a boolean error on call back
Cannot read property 'shouldBeUnique' of null
import {Component, Inject} from '@angular/core';
import {FormGroup, Validators, FormBuilder} from '@angular/forms';
import {UsernameValidators} from './usernameValidators'
@Component({
selector: 'signup-form',
templateUrl: 'app/signup-form.component.html'
})
export class SignUpFormComponent {
form: FormGroup;
constructor(@Inject(FormBuilder) fb: FormBuilder) {
this.form = fb.group({
username: ['', Validators.compose([
Validators.required,
UsernameValidators.cannotContainSpace
]), UsernameValidators.shouldBeUnique],
password: ['', Validators.required]
})
}
get username(): any {return this.form.get('username');}
get password(): any {return this.form.get('password');}
}
<form [formGroup]="form" (ngSubmit)="signup()">
<div class="form-group">
<label for="username">Username</label>
<input
id="username"
type="text"
class="form-control"
formControlName="username" placeholder="Username"
>
<div *ngIf="username.touched && username.errors">
<div *ngIf="username.errors.shouldBeUnique" class="alert alert-danger">This username is already taken</div>
</div>
</form>
import {FormControl} from '@angular/forms';
export class UsernameValidators {
static shouldBeUnique(control: FormControl) {
return new Promise((resolve, reject) => {
setTimeout(function(){
if (control.value == "mosh")
resolve({ shouldBeUnique: true});
else
resolve(null);
}, 1000)
});
}
}
Try using the safe navigation operator (?.)
to guard against null and undefined values in property paths.
<div *ngIf="username.touched && username.errors">
<div *ngIf="username.errors?.shouldBeUnique" class="alert alert-danger">This username is already taken</div>
</div>
This should resolve the error you are currently running into. Read more in the Angular 2 docs here:
https://angular.io/docs/ts/latest/guide/template-syntax.html#!#safe-navigation-operator