输入在Angular 2中有效时显示消息

时间:2018-04-17 03:14:35

标签: angular

我可以在我的2个输入上显示有效消息。即,使用以下代码的用户名和密码:

<div class="input-field col s6">
    <input class="validate" type="text" name="UserName" #UserName="ngModel" [(ngModel)]="user.UserName" required minlength="3">
    <label [attr.data-error]="UserName.errors != null ? (UserName?.errors.required ? 'This field is required.' : 'Minimum length is 3') : ''">UserName</label>
    <div class="validated" *ngIf="UserName.errors == null">Username validation has passed.</div>
</div>
<div class="input-field col s6">
    <input class="validate" type="password" name="Password" #Password="ngModel" [(ngModel)]="user.Password" required  minlength="3">
    <label [attr.data-error]="Password.errors != null ? (Password?.errors.required ? 'This field is required.' : 'Minimum length is 3') : ''">Password</label>
    <div class="validated" *ngIf="Password.errors == null">Password validation has passed.</div>
</div>

但是在我的电子邮件输入字段中,如果它无效,我可以显示错误消息,但即使我尚未在电子邮件输入字段中执行任何操作,我的有效消息也会显示。以下是我如何实现它:

<div class="input-field col s12">
    <input class="validate" type="text" name="Email" #Email="ngModel" [(ngModel)]="user.Email" [pattern]="emailPattern">
    <label data-error="Invalid email">Email</label>
    <div ng-messages="Email.$error" ng-show="userRegistrationForm.Email.$dirty"></div>
    <div class="validated" *ngIf="Email.errors == null">Email validation has passed.</div>
</div>
你能帮忙吗?谢谢。

1 个答案:

答案 0 :(得分:2)

您可以使用dirty来检查用户是否已在此字段中输入数据。请参阅以下内容:

<div class="input-field col s12">
<input class="validate" type="text" name="Email" #Email="ngModel" [(ngModel)]="user.Email" [pattern]="emailPattern">
<label data-error="Invalid email">Email</label>
<div ng-messages="Email.$error" ng-show="userRegistrationForm.Email.$dirty"></div>
<div class="validated" *ngIf="user.Email != '' && userRegistrationForm.controls.Email?.dirty && userRegistrationForm.controls.Email?.errors == null">Email validation has passed.</div>