【问题标题】:Angular 4: mismatch input fields with error messageAngular 4:输入字段与错误消息不匹配
【发布时间】:2017-12-15 15:17:36
【问题描述】:

我想在不创建新指令的情况下比较密码字段并确认密码,只需使用 ngModel 和 HTML。如果密码不匹配,我有一个提交按钮被阻止,并且工作正常。但是我想在用户重新输入(或提交)时显示跨度错误消息,到目前为止,在密码字段的第一次输入之后(当重新输入为空时)我收到错误消息。使用我拥有的代码,这是合乎逻辑的,但我想知道是否有可能在不使用验证器或指令的情况下拥有更好的用户体验?我已经尝试了几种方法,但没有任何效果......任何提示将不胜感激。代码:

<form #confirm="ngForm" novalidate>
          <mat-form-field class="full-width">
            <input matInput type="password" id="password" placeholder="New Password" name="password"
                   [(ngModel)]="loginValues.password" required>

          </mat-form-field>

          <mat-form-field class="full-width">
            <input matInput type="password" id="confirmPassword" placeholder="Retype Password" name="confirmPassword"
                   [(ngModel)]="loginValues.confirmPassword" required>

          </mat-form-field>
                <!--Error Message-->
            <span *ngIf="loginValues.confirmPassword  !== loginValues.password">{{ 'login.password_not_match' | translate }}</span>

          <div class="child-padding-top no-side-padding" fxLayoutAlign="end center" >
            <button class="button-login-register" [disabled]="loginValues.password !== loginValues.confirmPassword" mat-button color="primary"
                    (click)="clientNewPassword()" >{{ 'login.SUBMIT' | translate }}</button>
          </div>
        </form>

【问题讨论】:

  • 那么为什么要投反对票...

标签: javascript angular forms


【解决方案1】:

您不应该为 *ngIf 使用跨度,除非您出于某种目的使用跨度(向其中添加类等)。但似乎你只是用它来保存你的 *ngIf 语句,因为 *ngIf 必须被标记到一个元素。如果你打算这样做,你应该改用

<ng-container *ngIf=""></ng-container>. 

要回答您的问题,我认为您在不应用验证的情况下唯一可以做的就是添加更多逻辑。例如你可以这样做:

 <ng-container* ngIf="loginValues.confirmPassword !== loginValues.password 
    && loginValues.confirmPassword.length > 0 
    && loginValues.password.length > 0 ">
    {{ 'login.password_not_match' | translate }}
 </ng-container>

基本上,您所做的是更改它,以便在密码不匹配时并不总是显示错误,而是用户必须先填写两个输入。你还有其他事情可以做。例如你可以使用 ngTouched/ngDirty 等。你可以设置你喜欢的规则。

【讨论】:

  • 感谢您的回答,但是按照这种逻辑,我收到了一堆消息,我想我需要应用验证...
  • 我的错,非常感谢@David Anthony Acosta,它就像一个魅力:)
猜你喜欢
  • 1970-01-01
  • 2012-02-06
  • 1970-01-01
  • 2015-09-19
  • 2019-05-08
  • 1970-01-01
  • 2014-09-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多