从昨天开始为了熟练掌握上个月所学的 Angular4 入门知识,开始试卷写一个小后台项目来做练习,练习写登陆当中长时间的卡在了表单检验的过程中。现在把遇到的问题及解决方法一一罗列出来,方便日后遇到类似的问题时以做参考。
一、hasError 和 getError 的使用
hasError 的作用是检验用户在表单控件上输入的信息是否符合检验的标准,而 getError 则是在检验出用户输入错误时提示用户来纠正输入的信息。如下模板代码:
<div class="form-group has-feedback"> <input formControlName="mobile" type="number" class="form-control" placeholder="手机号"> <span class="glyphicon glyphicon-phone form-control-feedback"></span> <div class="alert alert-warning" [hidden]="_formModel.get('mobile').valid"> <span [hidden]="!_formModel.hasError('required', 'mobile')"> 请输入11位的手机号 </span> <span [hidden]="_formModel.hasError('required', 'mobile') || !_formModel.hasError('mobile', 'mobile')"> {{_formModel.getError('mobile', 'mobile')?.info}} </span> </div> </div>
当在使用时遇到传值错误,而导致了运行时检验的效果不如意,找了大半天的原因,后来发现还是有方法的。可以在控制器的中输入打印所有存在检验失败的代码:
let mobileValid: any = this._formModel.get('mobile').errors; console.log('mobileValid 的错误操作:' + JSON.stringify(mobileValid));
执行后会以 JSON 的格式来返回:
mobileValid 的错误操作:{"required":true,"mobile":{"info":"手机号码格式不正确"}}
而 hasError 和 getError 中的值也是相同的,如 hasError:
<!--required 是 JSON 格式错误中的 key--> <!--mobile 是表单的控件名--> <span [hidden]="!_formModel.hasError('required', 'mobile')">
而 getError 后面的 “?.info”则是如果检验到输入的字符错误则打印出现“{“info”:”手机号码格式不正确”}”的 value 里面的信息
转载请注明:隨習筆記 » Angular笔记:表单检验