我正在使用MEAN Stack和Angular 6开发应用程序。我已经实现了一个登录页面。当我单击登录按钮而不输入电子邮件和密码时,应该在相关的文本字段下方显示验证消息。
<small class="form-text error" *ngIf="email.invalid && email.touched && email.errors?.required">
Email is required!
</small>
<small class="form-text error" *ngIf="password.invalid && password.touched && password.errors?.required">
Password is required!
</small>
现在发生的事情是如果触摸文本字段并将其为空,则会显示错误消息。我也想要该功能,并且如果我们在不触摸文本字段的情况下单击提交按钮,它也应该显示该消息。 这是login.ts
login(): void {
if (!this.user.email || !this.user.password){
return;
}
this.errors = this.messages = [];
this.submitted = true;
this.service.authenticate(this.strategy, this.user).subscribe((result: NbAuthResult) => {
this.submitted = false;
if (result.isSuccess()) {
this.messages = result.getMessages();
} else {
this.errors = result.getErrors();
}
const redirect = result.getRedirect();
if (redirect) {
setTimeout(() => {
return this.router.navigateByUrl(redirect);
}, this.redirectDelay);
}
this.cd.detectChanges();
});
}
我尝试过的事情。
使用了一个布尔变量来提交尝试。
submitAttempt: boolean = false;
在文本字段为空时将其设置为true。
if (!this.user.email || !this.user.password){
this.submitAttempt=true;
return;
}
在html中使用它。
<small class="form-text error" *ngIf="email.invalid && email.touched && (email.errors?.required && submitAttempt)">
Email is required!
</small>
<small class="form-text error" *ngIf="password.invalid && password.touched && (password.errors?.required && submitAttempt)">
Password is required!
</small>
答案 0 :(得分:0)
请在ngif条件部分替换为此
* ngIf =“ formName.get('email')。touched && formName.get('email')。hasError('required')”>此字段为必填!
答案 1 :(得分:0)
您已按照正确的方向实施。只需稍作调整即可-
submitted
移动到函数顶部login(): void {
this.submitted = true; //<-- this should be at top
if (!this.user.email || !this.user.password){
return;
}
this.errors = this.messages = [];
this.service.authenticate(this.strategy, this.user).subscribe((result: NbAuthResult) => {
this.submitted = false;
if (result.isSuccess()) {
this.messages = result.getMessages();
} else {
this.errors = result.getErrors();
}
const redirect = result.getRedirect();
if (redirect) {
setTimeout(() => {
return this.router.navigateByUrl(redirect);
}, this.redirectDelay);
}
this.cd.detectChanges();
});
}
<small class="form-text error" *ngIf="email.invalid && ( email.touched || submitted) && (email.errors?.required)">
Email is required!
</small>