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

Angular Material中matSuffix按钮回车异常触发问题如何解决?

问题根因

该现象是HTML原生表单的默认行为导致,不属于Angular Material的bug:

  • 位于<form>标签内的<button>如果没有显式声明type属性,默认值为submit
  • 当用户在表单任意输入框按下回车时,浏览器会自动触发表单内第一个submit类型按钮的点击事件,同时将焦点移动到该按钮关联的表单控件上,也就是你遇到的密码输入框获得焦点、显隐按钮被触发的问题。

解决方案

只需要给作为matSuffix的按钮显式指定type="button"即可,修改后的代码如下:

<div class="example-container">
  <form (ngSubmit)="handleSubmit()"> <!-- 若需要表单提交逻辑,绑定ngSubmit即可 -->
    <mat-form-field>
      <input
        matInput
        placeholder="Enter your password"
        [type]="hide ? 'password' : 'text'"
      />
      <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>
    </mat-form-field>

    <mat-form-field>
      <input
        matInput
        placeholder="Amount"
        type="number"
        class="example-right-align"
      />
      <span matPrefix>$&nbsp;</span>
      <span matSuffix>.00</span>
    </mat-form-field>
    <!-- 如果有表单提交按钮,显式设为type="submit",不需要显示可以设为隐藏 -->
    <button type="submit" style="display: none;"></button>
  </form>
</div>

如果需要回车正常触发表单提交,给form绑定(ngSubmit)事件处理提交逻辑即可,回车时会优先触发该提交事件,不会误触发其他操作按钮。

内容的提问来源于stack exchange,提问作者Demiro-FE-Architect

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 01:00:05