我有一个自定义的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;
}
}
答案 0 :(得分:3)
您的username
formControl不是可直接访问的类变量。您可以通过FormGroup
userNameGroup
访问它。
<div *ngIf="usernameGroup.controls['username'].errors?.cannotContainSpace">
或正如Manuel Zametter所说:
<div *ngIf="usernameGroup.controls.username.errors?.cannotContainSpace">
?.
是安全的导航操作符,如果是undefined
或null
,则会检查错误。