角度反应表单 - 更改输入类型触发表单验证

alv*_*peo 1 rxjs angular-material angular rxjs6

我有一个用 Angular 11.2.7 和 Angular Material 制作的简单注册表单。这是堆栈闪电战

我将密码字段的可见性更改为最后 3 秒,然后它们的状态更改回“密码”。因此,当用户单击任何密码控件中的“眼睛”时,密码文本将以明文显示,然后在 3 秒内变回点。

但问题是,此状态更改会触发整个表单验证,并且所有无效的内容都会看起来“无效”(呈红色)。谁能告诉我为什么吗?

另外,我必须对我的 Observables 使用多播,但我可能做得不对。我不知道。

Osc*_*lez 6

您好,问题是表单中没有任何定义类型的按钮就像表单的提交按钮,必填字段将显示错误。只需添加type='button' 到按钮标签即可。

form [formGroup]="frm">
  <div class="example-container">
    <mat-form-field appearance="fill">
      <mat-label>Email</mat-label>
      <input
        type="email"
        matInput
        placeholder="yourname@domain.com"
        formControlName="email"
        required
      />
      <mat-error *ngIf="isTouchedAndInvalid('email')">{{ getErrorMessage("email") }}</mat-error>
    </mat-form-field>
  </div>
  <div class="example-container">
    <mat-form-field appearance="fill">
      <mat-label>Enter your password</mat-label>
      <input matInput [type]="(passwordType$ | async)!" />
      <button
        mat-icon-button
        matSuffix
        (click)="showPassword()"
        [attr.aria-label]="'Hide password'"
        type='button'
      >
        <mat-icon>{{ hidePassVisibility$ | async }}</mat-icon>
      </button>
    </mat-form-field>

    <mat-form-field appearance="fill">
      <mat-label>Confirm password</mat-label>
      <input matInput [type]="(passwordType$ | async)!" />
      <button
        mat-icon-button
        matSuffix
        (click)="showPassword()"
        [attr.aria-label]="'Hide password'"
        type='button'
      >
        <mat-icon>{{ hidePassVisibility$ | async }}</mat-icon>
      </button>
    </mat-form-field>
  </div>
</form>
Run Code Online (Sandbox Code Playgroud)