Angular2 / 4无法将输入字段绑定到ngControl - 无法读取属性'错误'未定义的

时间:2017-06-19 11:37:38

标签: javascript angular customvalidator

我有一个自定义的Validator来检查输入字段中的空格,但我不明白为什么输入字段未定义到构造函数。

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

1 个答案:

答案 0 :(得分:3)

您的username formControl不是可直接访问的类变量。您可以通过FormGroup userNameGroup访问它。

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

或正如Manuel Zametter所说:

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

?.是安全的导航操作符,如果是undefinednull,则会检查错误。

Plunker