You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular Material密码框按回车触发显示切换而非提交表单的解决方法

解决Angular登录表单中密码框回车触发显示/隐藏按钮的问题

问题出在密码框右侧的显示/隐藏按钮上——表单内的<button>元素默认type是"submit",当你在输入框按下回车键时,浏览器会自动触发表单中第一个submit类型的按钮,刚好就是这个显示密码的按钮,所以才会触发状态切换而非登录提交。

有两种简单的修复方式:

方法1:给显示/隐藏按钮指定type="button"

直接修改密码框的按钮,明确它是普通按钮,不会被当作提交按钮:

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

方法2:优化表单提交逻辑(更规范的做法)

给表单绑定ngSubmit事件,同时把登录按钮设为submit类型,这样回车会直接触发表单提交,也符合Angular表单的最佳实践:

修改后的完整模板代码:

<div style="text-align: center" class="centered">
  <form [formGroup]="form" (ngSubmit)="login()"> <!-- 绑定ngSubmit事件 -->
    <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"
              type="button"> <!-- 明确为普通按钮 -->
        <mat-icon>{{passwordVisible ? 'visibility' : 'visibility_off'}}</mat-icon>
      </button>
    </mat-form-field>
    <br>
    <button type="submit" mat-raised-button>Login</button> <!-- 设为submit类型 -->
    <button (click)="navigateToRegister()" mat-raised-button color="primary" style="margin-left: 10px" type="button">Register</button> <!-- 注册按钮也建议指定type避免意外提交 -->
  </form>
</div>

这样修改后,不管在用户名还是密码框按回车,都会直接触发login()方法提交表单,同时显示/隐藏按钮也不会再被回车触发。

内容的提问来源于stack exchange,提问作者Ronnie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 01:20:38