Search code examples
javascriptangularcustomvalidator

Angular2/4 Cannot bind input field to ngControl - Cannot read property 'errors' of undefined


I have a custom Validator to check for spaces in input field, but I cant understand why input field is being undefined to the constructor.

CustomValidationComponent:

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

@Component({
  selector: 'custom-validation',
  template: `
    <div [formGroup]="usernameGroup">
      <input type="text" placeholder="Name" formControlName="username">
      <div *ngIf="username.errors.cannotContainSpace"> Without spaces! </div>
    </div>
  `
})

export class CustomValidationFormComponent {

  usernameGroup: FormGroup;

  constructor(fb: FormBuilder){
    this.usernameGroup = fb.group({
      username: ['', UsernameValidators.cannotContainSpace],
    });
  }

UsernameValidator:

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

export class UsernameValidators {
  static cannotContainSpace(control: FormControl){
    if (control.value.indexOf(' ') >= 0) 
      return { cannotContainSpace: true };

        return null;
  }
}

PLUNKER


Solution

  • Your username formControl is not a class variable to access directly. You can access it through the FormGroup which is userNameGroup.

      <div *ngIf="usernameGroup.controls['username'].errors?.cannotContainSpace">
    

    Or as Manuel Zametter mentioned:

      <div *ngIf="usernameGroup.controls.username.errors?.cannotContainSpace">
    

    The ?. is safe navigation operator which does a check on errors if it is undefined or null.

    Plunker