Angular中错误消息未显示在UI上
创始人
2024-10-31 01:30:41
0
  1. 确认错误消息已经被添加到表单控件中的错误数组中。
  2. 确保在UI中对应的错误消息指令已经添加。
  3. 确认表单控件上添加了对应的错误消息指令。
  4. 确认表单控件绑定的ngModel或formControl中已经包含了Validators。
  5. 确认表单控件绑定的ngModel或formControl中设置了错误消息。

示例:

在模板中添加错误消息指令:

Username is required.

在指令中显示错误消息:

import { Directive, HostBinding, HostListener } from '@angular/core';

@Directive({ selector: '[appErrorMessage]' }) export class ErrorMessageDirective { @HostBinding('class.error-message') hasErrorMessage = true;

constructor() { }

@HostListener('input', ['$event.target']) onInput(target: HTMLInputElement) { const control = target.validity;

if (control.valid) {
  this.hasErrorMessage = false;
} else {
  this.hasErrorMessage = true;
}

} }

在ngModel或FormControl中设置错误消息:

ngOnInit() { this.myForm = new FormGroup({ name: new FormControl('', [ Validators.required, Validators.minLength(4) ]), email: new FormControl('', [ Validators.required, Validators.pattern('[^ @]@[^ @]') ]) }); }

get name() { return this.myForm.get('name'); }

get email() { return this.myForm.get('email'); }

getErrorMessage(control: AbstractControl) { return control.hasError('required') ? 'You must enter a value' : control.hasError('email') ? 'Not a valid email' : control.hasError('minlength') ? Must be at least ${control.errors.minlength.requiredLength} characters : ''; }

相关内容

热门资讯

做出回应!九天大厅辅助器!好像... 做出回应!九天大厅辅助器!好像有挂辅助器(有挂透视)-哔哩哔哩1、起透看视 九天大厅辅助器辅助软件价...
日前!长春科乐天天踢辅助!真是... 日前!长春科乐天天踢辅助!真是真的有辅助平台(有挂讲解)-哔哩哔哩1、打开软件启动之后找到中间准星的...
随着!打两圈绝对有辅助!确实真... 随着!打两圈绝对有辅助!确实真的是有辅助软件(有挂教程)-哔哩哔哩1、玩家可以在打两圈绝对有辅助线上...
今天下午!闲逸辅助软件制作!确... 今天下午!闲逸辅助软件制作!确实是有辅助神器(有挂方法)-哔哩哔哩1、闲逸辅助软件制作辅助器安装包、...
截至目前!朋朋政和软件辅助器!... 截至目前!朋朋政和软件辅助器!一直有挂辅助器(真是有挂)-哔哩哔哩所有人都在同一条线上,像星星一样排...
相较于以往!手机透视辅助器ap... 相较于以往!手机透视辅助器app!确实存在有辅助神器(有挂助手)-哔哩哔哩1、上手简单,内置详细流程...
备受关注的!同城乐吧乐享版51... 备受关注的!同城乐吧乐享版510k辅助!竟然是真的辅助下载(有挂分析)-哔哩哔哩1、同城乐吧乐享版5...
目前!乐乐休闲游戏辅助!一贯真... 目前!乐乐休闲游戏辅助!一贯真的是有辅助工具(真实有挂)-哔哩哔哩1、首先打开乐乐休闲游戏辅助辅助器...
来临!微信多乐小程序游戏破解器... 来临!微信多乐小程序游戏破解器!一贯是有辅助平台(确实有挂)-哔哩哔哩1、超多福利:超高返利,海量正...
近年来!闲逸有没有辅助软件功能... 近年来!闲逸有没有辅助软件功能!好像存在有辅助神器(有挂教程)-哔哩哔哩该软件可以轻松地帮助玩家将闲...