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

Angular Material登录表单回车触发密码显隐而非提交的解决请求

解决Angular Material登录表单回车键触发密码显隐按钮的问题

问题根源在于密码输入框后的显隐按钮未指定type属性,在表单环境中,按钮默认的type值为submit,导致按下回车键时,浏览器会优先触发这个按钮的点击事件,而非表单的提交按钮。

解决方案一(推荐):指定按钮类型为button

给密码显隐按钮添加type="button",明确它不是提交按钮,这样回车键就会触发表单的提交操作:

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

解决方案二:阻止按钮的默认提交行为

如果不想修改按钮类型,可以在点击事件中调用$event.preventDefault(),阻止按钮触发表单提交:

<button mat-icon-button matSuffix (click)="hide = !hide; $event.preventDefault()" [attr.aria-label]="'Hide password'" [attr.aria-pressed]="hide">
  <mat-icon>{{hide ? 'visibility_off' : 'visibility'}}</mat-icon>
</button>

推荐使用第一种方案,因为它更符合语义化规范,清晰定义了按钮的功能类型,避免潜在的表单行为冲突。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 18:03:31