HTML
<form nz-form [formGroup]="formGroup">
<nz-form-item>
<nz-form-label nzFor="username">
<span translate>Username</span>
</nz-form-label>
<nz-form-control nzHasFeedback>
<input nz-input name="username" type="text" id="username" formControlName="username"
[placeholder]="'Enter Username' | translate" (keydown.space)="$event.preventDefault()" />
<nz-form-explain *ngIf="
(formGroup.get('username')?.dirty && formGroup.get('username')?.errors) ||
formGroup.get('username')?.pending
">
<ng-container *ngIf="formGroup.get('username')?.hasError('required')">
Username is required
</ng-container>
<ng-container *ngIf="formGroup.get('username')?.hasError('duplicated')">
Username already exists. Please try different username
</ng-container>
<ng-container *ngIf="formGroup.get('username')?.pending">
Validating...
</ng-container>
</nz-form-explain>
</nz-form-control>
</nz-form-item>
</form>
*** TS ****
import { FormGroup, FormBuilder, Validators, FormControl, ValidationErrors } from '@angular/forms';
userNameAsyncValidator = (control: FormControl) =>
new Observable((observer: Observer<ValidationErrors | null>) => {
setTimeout(() => {
if (control.value === 'JasonWood') {
observer.next({ error: true, duplicated: true });
} else {
observer.next(null);
}
observer.complete();
}, 1000);
});
createFormGroup(data?: Partial<User>) {
const dataObj = {
id: [data && data.id],
username: [
{
value: (data && data.username) || '',
disabled: data instanceof User
},
[Validators.required],
[this.userNameAsyncValidator]
]
}
return this.fb.group(dataObj);
}
user.module
imports: [
CommonModule,
UsersRoutingModule,
FormsModule,
ReactiveFormsModule,
PageTableFilterModule,
CellRenderersModule,
NzDrawerModule,
NzFormModule,
NzInputModule,
NzSelectModule,
NzDividerModule
]
как исправить ошибку: ERROR TypeError: Cannot read property 'validate' of undefined
.
Я хочу, чтобы имя пользователя имело валидацию, равную already exists
и username is required
.
Я добавил userNameAsyncValidator, после добавления имени пользователя он начинает вызывать ошибку ERROR TypeError: Cannot read property 'validate' of undefined
. но когда я пытаюсь удалить userNameAsyncValidator в имени пользователя, у него нет ошибки.
как это исправить?
ОШИБКА:
at normalizeAsyncValidator (forms.js:930)
at Array.map (<anonymous>)
at composeAsyncValidators (forms.js:2150)
at coerceToAsyncValidator (forms.js:2501)
at new FormControl (forms.js:3236)
at FormBuilder.push../node_modules/@angular/forms/fesm5/forms.js.FormBuilder.control (forms.js:6462)
at FormBuilder.push../node_modules/@angular/forms/fesm5/forms.js.FormBuilder._createControl (forms.js:6502)
at forms.js:6488
at Array.forEach (<anonymous>)
at FormBuilder.push../node_modules/@angular/forms/fesm5/forms.js.FormBuilder._reduceControls (forms.js:6487)```