简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM