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 : ''; }

相关内容

热门资讯

微扑克ai辅助!aapoker... 微扑克ai辅助!aapoker外挂,(wePOKE)竟然真的有挂,科技教程(有挂细节);1、金币登录...
透视有挂!wepoker脚本,... 透视有挂!wepoker脚本,德普之星透视辅助ios,玩家攻略推荐(有挂透明);1)辅助挂:进一步探...
微扑克ai辅助!微扑克辅助机器... 微扑克ai辅助!微扑克辅助机器人,(wePOke)真是是真的有挂,透明挂教程(有挂方法)1、该软件可...
透视透视挂!aapoker透视... 透视透视挂!aapoker透视脚本安装包,hhpoker透视方法,揭秘(有挂教程)软件透明挂微扑克w...
wpk有透视辅助!wepoke... wpk有透视辅助!wepoke辅助技巧,(WEPoke)切实是有挂,透明挂教程(有挂教程)1、用户打...
透视安卓版!hhpoker透视... 透视安卓版!hhpoker透视方法,aapoker辅助插件工具下载,一秒答解(有挂总结)1、进入到a...
微扑克wpk透视辅助!wepo... 微扑克wpk透视辅助!wepower有外挂,(wEpOke)总是真的是有挂,分享教程(有挂工具);1...
透视挂透视!aapoker辅助... 透视挂透视!aapoker辅助插件工具下载,wpk辅助购买,实测揭晓(有挂技巧)1、起透看视 aap...
wpk透视辅助!微扑克系统发牌... wpk透视辅助!微扑克系统发牌规律,(wEPoke)原来真的是有挂,扑克教程(有挂方法)1、起透看视...
透视玄学!wepoker辅助器... 透视玄学!wepoker辅助器怎么用,红龙poker辅助,玩家必备攻略(有挂规律)1、系统规律教程、...