我想在表单的输入字段和消息Password is invalid
周围以及用户输入的密码与设置的密码不匹配时显示红色边框。
当我输入与设置的密码不同的内容但未显示该消息时,我会看到红色边框,表明存在错误。花了几个小时检查我的代码后,我一直无法弄清楚问题出在哪里,所以请仔细查看我的代码并指出错误
password.validators.ts
import { AbstractControl, ValidationErrors } from "@angular/forms";
export class PasswordValidators {
static matchOldPassword(
control: AbstractControl
): Promise<ValidationErrors | null> {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (control.value !== "1234") resolve({ matchOldPassword: true });
else resolve(null);
}, 2000);
});
}
}
password-change.component.ts
import { PasswordValidators } from "./password.validator";
import { FormGroup, FormControl, Validators } from "@angular/forms";
import { Component } from "@angular/core";
@Component({
selector: "password-change",
templateUrl: "./password-change.component.html",
styleUrls: ["./password-change.component.css"]
})
export class PasswordChangeComponent {
form = new FormGroup({
oldPassword: new FormControl(
"",
Validators.required,
PasswordValidators.matchOldPassword
)
});
}
password-change.component.html
<form [formGroup]="form">
<div class="form-group">
<label for="oldPassword" class="font-weight-bold">Old Password</label>
<input
formControlName="oldPassword"
type="password"
id="oldPassword"
class="form-control"
/>
<div
*ngIf="oldPassword.touched && oldPassword.pristine"
class="text-danger"
>
<div *ngIf="oldPassword.errors.required">Old password is required.</div>
<div *ngIf="oldPassword.errors.matchOldPassword">
Old password is not valid.
</div>
</div>
</div>
</form>
答案 0 :(得分:1)
从包裹oldPassword.pristine
中删除div
。修改字段后,您的if
变得虚假,因为它不再是原始数据,因此不会显示整个div。否则,您的代码看起来不错!因此,您的包装div应该如下所示:
<div *ngIf="oldPassword.touched">