angular - Show form error without field blur in angular
问题描述
In my application, I am trying angular validator
. If the form is already filled with data, then the validation is perfect. But if no data is filled initially and if I click on the button, then it is not showing the errors. But if I click on some fields and blur, then it will show the error for that field.
How can I make the error show when click on the button?
validation.service.ts
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class ValidationService {
constructor() { }
static getValidatorErrorMessage(validatorName: string, validatorValue?: any) {
const config = {
required: 'validation.required',
minlength: `Minimum length is ${validatorValue.requiredLength}`,
email: 'validation.email',
};
return config[validatorName];
}
}
validation-message.component.ts
import { Component, Input } from '@angular/core';
import { FormControl } from '@angular/forms';
import { ValidationService } from '../../services/validation/validation.service';
@Component({
selector: 'app-errorMessages',
template: `<div *ngIf="errorMessage !== null">{{errorMessage | translate}}</div>`
})
export class ValidationMessagesComponent {
@Input() control: FormControl;
constructor() { }
/**
* Function to get the form validation error message
*
* @readonly
* @memberof ValidationMessagesComponent
*/
get errorMessage() {
for (const propertyName in this.control.errors) {
if (this.control.errors.hasOwnProperty(propertyName) && this.control.touched) {
return ValidationService.getValidatorErrorMessage(propertyName, this.control.errors[propertyName]);
}
}
return null;
}
}
HTML portion to show the error
<app-errorMessages [control]="userForm.controls.userFullName" class="error-msg messages text-left text-danger"></app-errorMessages>
Button to initiate submit
<button type="button" class="btn btn-primary btn-lg btn-block" ngIf="submitFlag" (click)="onSubmit()">Save</button>
Functions associated with submit
onSubmit(): any {
// Component points data to the module and module points to the http service
// use the retun value to trigger a toast Message.
console.log(this.userForm);
if (!this.validateUserForm()) {
console.log('Show errors');
return false;
}
this.userService.createNewUser(this.userForm.value);
}
validateUserForm() {
if (this.userForm.invalid) {
return false;
}
return true;
}
解决方案
你希望你的条件看起来更像这样:
if (this.control.errors.hasOwnProperty(propertyName) && (this.control.touched || this.control.submitted))
然后您还需要在表单元素中使用 ngSubmit 指令并更改您的按钮类型以提交以使其工作
推荐阅读
- javascript - @input 在相同组件角度问题的不同实例中
- kubernetes - 使用 terraform 动态连接到 GKE 集群
- javascript - firebase 创建用户承诺
- python - 使用Biopython从python中的.fasta基因中提取基因起始位置
- javascript - 无法找到按钮以查找其禁用状态以进行测试
- python - 文本未知原因的 Tkinter 消息换行
- ios - 在 SWIFT 5 中点击时无法更改 UIImage systemName 图像
- sql-server - VBA使用'编写SQL字符串而没有被注释掉?
- javascript - 在拦截器中手动设置 auth 'Cookie' 是否安全?
- arrays - 在二维数组中查找整数行