【发布时间】:2021-03-17 09:04:35
【问题描述】:
我有一个自定义验证器来验证我的数据库中是否存在序列号。 当找不到序列号但我做不到时,我想在表单的字段中显示特定的错误消息。我尝试了不同的方法,但结果并不好。 当我尝试在我的模板中插入此代码时
<div *ngIf="deviceInfos.controls.serial.errors && serial != null">
Error
</div>
即使在用户输入字段之前,错误消息也会显示。 我是 Angular 的新手,我实际上迷失在这个问题中。
这是我的自定义验证器
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { AbstractControl, AsyncValidator, FormControl } from '@angular/forms';
import { map, catchError } from 'rxjs/operators';
import { of } from 'rxjs';
@Injectable({
providedIn: 'root',
})
export class HttpRequestValidation implements AsyncValidator {
constructor(private http: HttpClient) {}
validate = (control: AbstractControl) => {
const { value } = control;
console.log(value);
return this.http.get<any>(`http://127.0.0.1/backend/api-vitoapp/verify-serial.php?serial=${value}`)
.pipe(
map(() => {
return null;
}),
catchError((err) => {
console.log(err);
return of (err);
})
);
};
}
这是我的组件的一部分
deviceSelected : any;
serial = new FormControl('');
constructor(private fb: FormBuilder,
private hardwareCheckService: HardwareCheckService) {
}
ngOnInit() {
this.deviceInfos = this.fb.group({
serial: [null, [Validators.required, this.httpRequestValidation.validate]],
deviceType: [this. deviceTypeOptions[0]],
});
}
有人可以帮助我吗? 非常感谢。
【问题讨论】:
标签: angular typescript angular-reactive-forms