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



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

自定义验证组件:

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],
    });
  }

用户名验证器:

import {FormControl} from '@angular/forms';
export class UsernameValidators {
  static cannotContainSpace(control: FormControl){
    if (control.value.indexOf(' ') >= 0) 
      return { cannotContainSpace: true };
        return null;
  }
}

普容克

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

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

或者正如曼努埃尔·扎梅特(Manuel Zametter(提到的:

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

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

普伦克

相关内容

最新更新