2016-12-25 36 views
2

如何在Angular 2.2.0中顯示錯誤信息,僅當輸入具有類接觸時才顯示?Angular 2僅當輸入類是「ng-touch」時才顯示錯誤消息?

<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> 

回答

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