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

相关内容

热门资讯

透视真的"xpoke... 透视真的"xpoker辅助工具"详细辅助德州教程(固有真的有挂)1、玩家可以在xpoker辅助工具软...
透视了解"hh po... 透视了解"hh poker软件"详细辅助揭秘教程(一直是真的有挂)1、不需要AI权限,帮助你快速的进...
透视智能ai"soh... 《透视智能ai"sohoo辅助"详细辅助力荐教程(确实真的有挂)》 sohoo辅助软件透明挂更新公告...
透视辅助"wepok... 透视辅助"wepoker辅助脚本"详细辅助实用技巧(起初是真的有挂);亲真的是有正版授权,小编(透视...
透视挂透视"约局吧德... 此外,数据分析德州(约局吧德州有挂吗)辅助神器app还具备辅助透视行为开挂功能,通过对客户约局吧德州...
透视黑科技"wepo... 透视黑科技"wepoker有透视吗"详细辅助AI教程(好像存在有挂);大神普及一款德州ai内幕,确定...
透视系统"aa po... 透视系统"aa poker透视软件"详细辅助解密教程(好像是真的有挂)是一款可以让一直输的玩家,快速...
透视计算"poker... 您好,pokernow辅助工具这款游戏可以开挂的,确实是有挂的,需要了解加微【136704302】很...
透视ai"we po... 1、透视ai"we poker辅助器v3.3"详细辅助可靠技巧(固有是有挂)。2、we poker辅...
透视挂透视"有没有人... 透视挂透视"有没有人wepoker"详细辅助必胜教程(切实是真的有挂)关于有没有人wepoker机制...