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

相关内容

热门资讯

透视好友"wepok... 透视好友"wepoker游戏安装教程"详细辅助wpk教程(透视破解版软件)是由北京得wepoker游...
透视好友房"拱趴大菠... 透视好友房"拱趴大菠萝万能挂图解"详细辅助辅助教程(可以破解游戏方法)1、不需要AI权限,帮助你快速...
透视黑科技"红龙po... 透视黑科技"红龙poker有辅助吗"详细辅助安装教程(万能挂透明);最新版2024是一款经典耐玩的益...
透视免费"agpok... 透视免费"agpoker辅助"详细辅助普及教程(游戏安装教程软件);1.agpoker辅助 ai辅助...
透视肯定"约局吧透视... 透视肯定"约局吧透视挂下载"详细辅助必赢教程(底牌透视技巧)1、很好的工具软件,可以解锁游戏的ai质...
透视辅助"wepok... 透视辅助"wepoker轻量版透视方法"详细辅助详细教程(辅助工具教程);wepoker轻量版透视方...
透视规律"aapok... 透视规律"aapoker怎么选牌"详细辅助高科技教程(可以免费玩技巧);实战中需综合运用上述技巧,并...
透视教学"wepok... 透视教学"wepoker辅助器"详细辅助解密教程(私人辅助器软件)1、很好的工具软件,可以解锁游戏的...
透视安卓版"wepo... 透视安卓版"wepoker透视有用吗"详细辅助wepoke教程(俱乐部辅助透视),支持语音通讯、好友...
透视游戏"智星菠萝辅... 透视游戏"智星菠萝辅助"详细辅助wepoke教程(辅助器如何使用教程)是由北京得智星菠萝辅助黑科技有...