html 角材料隐藏密码在输入时切换

whitzsjs  于 2022-12-09  发布在  其他
关注(0)|答案(2)|浏览(107)

我是angular的新手,我有一个项目,已经有一个用户名和密码输入的登录。密码输入有一个按钮来显示密码。问题是,当我在密码输入字段,我按回车键,它切换按钮来显示密码,而不是提交表单。我该如何改变呢?

组件. html

<div style="text-align: center" class="centered">
  <form [formGroup]="form">
    <br>
    <mat-form-field appearance="fill">
      <mat-label>Username</mat-label>
      <input name="username" formControlName="username" matInput>
    </mat-form-field>
    <br>
    <mat-form-field appearance="fill">
      <mat-label>Password</mat-label>
      <input name="password" formControlName="password" matInput [type]="passwordVisible ? 'text' : 'password'">
      <button mat-icon-button matSuffix (click)="passwordVisible = !passwordVisible" [attr.aria-label]="'Hide password'"
              [attr.aria-pressed]="!passwordVisible">
        <mat-icon>{{passwordVisible ? 'visibility' : 'visibility_off'}}</mat-icon>
      </button>
    </mat-form-field>
    <br>
    <button (click)="login()" mat-raised-button>Login</button>
    <button (click)="navigateToRegister()" mat-raised-button color="primary" style="margin-left: 10px">Register</button>
  </form>
</div>
2skhul33

2skhul331#

buttonDefault type是可能导致此问题的submit请尝试将显示/隐藏按钮type更改为button,类似于

<button type="button" mat-icon-button matSuffix (click)="passwordVisible = !passwordVisible" [attr.aria-label]="'Hide password'"
              [attr.aria-pressed]="!passwordVisible">
        <mat-icon>{{passwordVisible ? 'visibility' : 'visibility_off'}}</mat-icon>
      </button>
ttcibm8c

ttcibm8c2#

我最近也偶然发现了这个问题,并能够使用下面的方法解决它。
如果您在密码输入字段中按Enter键,则会调用方法onClickRevealPassword。此操作会导致一个名为pointerType的事件,您可以使用此方法检测该事件,并保持密码字段不显示纯密码值。请查看并使用您的组件进行试验。

<mat-form-field appearance="fill">
  <mat-label>Password</mat-label>
  <input name="password" formControlName="password" matInput [type]="passwordVisible ? 'text' : 'password'">
  <button mat-icon-button matSuffix (click)="passwordVisible = !passwordVisible; onClickRevealPassword($event)" [attr.aria-label]="'Hide password'"
          [attr.aria-pressed]="!passwordVisible">
    <mat-icon>{{passwordVisible ? 'visibility' : 'visibility_off'}}</mat-icon>
  </button>
</mat-form-field>

onClickRevealPassword(event) {
  event.preventDefault();
  // Prevent revealing the password when enter button is pressed.
  if (event?.pointerType) {
    this.passwordVisible = !this.passwordVisible;
  }
}

相关问题