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

相关内容

热门资讯

9分钟了解!we-poker软... 9分钟了解!we-poker软件(辅助挂)果然有挂(真实有挂辅助方法)1、全新机制【ai辅助工具激活...
推荐十款!wepoker有什么... 推荐十款!wepoker有什么规律(辅助挂)其实有挂(有挂工具辅助脚本)1、打开软件启动之后找到中间...
传递经验!hhpoker德州作... 传递经验!hhpoker德州作弊(辅助挂)一贯有挂(有挂方式辅助技巧)破解侠是真的助透视。每个模型中...
六分钟了解!aapoker怎么... 六分钟了解!aapoker怎么设置提高好牌几率(辅助挂)竟然真的有挂(有挂总结辅助技巧)一、可以开透...
免费测试版!wejoker开挂... 免费测试版!wejoker开挂(辅助挂)真是真的是有挂(有挂规律辅助插件)是不是有人用挂微扑克wpk...
最新通报!云扑克有透视吗(辅助... 最新通报!云扑克有透视吗(辅助挂)竟然真的是有挂(有挂方针辅助软件)1、模拟器是什么优化,俱乐部是真...
重大通报!aapoker辅助插... 重大通报!aapoker辅助插件工具(辅助挂)其实有挂(新版有挂辅助工具)1、下载好脚本下载之后点击...
揭秘!黑侠破解wepoker(... 揭秘!黑侠破解wepoker(辅助挂)确实是有挂(有挂方法辅助器)1、辅助器安装包、辅助器2、分享自...
查到实测辅助!hhpoker辅... 查到实测辅助!hhpoker辅助器视频(辅助挂)一贯是有挂(发现有挂辅助攻略)1、玩家可以在透视最简...
一分钟秒懂!wepoker辅助... 一分钟秒懂!wepoker辅助真的假的(辅助挂)果然有挂(详细教程辅助插件)一、可以开透视的定义与意...