Angular 2仅在输入类被触摸时显示错误消息"?

时间:2016-12-25 14:44:00

标签: angular

如果输入有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>

1 个答案:

答案 0 :(得分:4)

首先,您需要有一个变量来保存firstName模型#fistName="ngModel"。然后,您可以阅读firstName状态,如pristinedirtytouchedvalid等。

<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