seus seus - 9 months ago 56
AngularJS Question

Angular 2 Cannot read property 'x' of null

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

Here is my component

import {Component, Inject} from '@angular/core';
import {FormGroup, Validators, FormBuilder} from '@angular/forms';
import {UsernameValidators} from './usernameValidators'

selector: 'signup-form',
templateUrl: 'app/signup-form.component.html'
export class SignUpFormComponent {

form: FormGroup;

constructor(@Inject(FormBuilder) fb: FormBuilder) {
this.form ={
username: ['', Validators.compose([
]), UsernameValidators.shouldBeUnique],
password: ['', Validators.required]

get username(): any {return this.form.get('username');}
get password(): any {return this.form.get('password');}


Here is my component.html

<form [formGroup]="form" (ngSubmit)="signup()">
<div class="form-group">
<label for="username">Username</label>
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>

Here is my validator class where the promise is being made

import {FormControl} from '@angular/forms';

export class UsernameValidators {

static shouldBeUnique(control: FormControl) {
return new Promise((resolve, reject) => {
if (control.value == "mosh")
resolve({ shouldBeUnique: true});
}, 1000)


Answer Source

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>

This should resolve the error you are currently running into. Read more in the Angular 2 docs here:!#safe-navigation-operator