如果输入有ng-touch类,如何在Angular 2.2.0中显示错误信息?
<form #myForm='ngForm' (ngSubmit)='onSubmit(submit)' (submit)="preventDefault($event)">
<input type="text" name="firstName" ngModel required>
<div class="error-mesg"> Name is required </div>
<button type="submit" [disabled]="!myForm.form.valid">
</form>
答案 0 :(得分:4)
首先,您需要有一个变量来保存firstName模型#fistName="ngModel"
。然后,您可以阅读firstName
状态,如pristine
,dirty
,touched
,valid
等。
<input type="text" name="firstName" ngModel required
#fistName="ngModel">
<div class="error-mesg" [hidden]="fistName.valid || (fistName.pristine && !myForm.submitted)">
Name is required
</div>
有关详细说明,请在此处阅读此文章:https://scotch.io/tutorials/using-angular-2s-template-driven-forms