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

如何在ng-autocomplete组件上禁用Chrome浏览器自动填充功能

可行解决方案如下:

方案1:直接使用组件内置的输入属性传递配置(优先推荐)

你使用的angular-ng-autocomplete库提供了inputAttrs参数,可以直接向内部封装的原生input元素传递属性,无需手动操作DOM,在你的现有组件代码上添加对应配置即可:

<ng-autocomplete
  [data]="countryObject"
  [searchKeyword]="keyword"
  [initialValue]="initialVal"
  placeholder="Search Country"
  (selected)="selectEvent($event)"
  (inputChanged)='onChangeSearch($event)'
  (inputFocused)='onFocused($event)'
  [itemTemplate]="itemTemplate"
  [notFoundTemplate]="notFoundTemplate"
  formControlName="country"
  [ngClass]="{ 'is-invalid': submitted && f.country.errors }"
  <!-- 新增下面这行配置 -->
  [inputAttrs]="{ autocomplete: 'new-password', autocorrect: 'off', autocapitalize: 'off', spellcheck: 'false' }"
  required
  >
</ng-autocomplete>

注:Chrome对autocomplete="off"的识别存在兼容问题,使用new-password或者任意不被Chrome自动填充规则识别的自定义值(比如no-autofill),禁用效果更稳定。

方案2:手动获取内部input元素设置属性

如果你的库版本较低不支持inputAttrs参数,可以通过ViewChild获取组件实例后,手动给内部原生input添加属性:

  1. 在组件ts文件中添加逻辑:
import { ViewChild, AfterViewInit } from '@angular/core';
import { NgAutocompleteComponent } from 'angular-ng-autocomplete';

export class YourComponent implements AfterViewInit {
  @ViewChild(NgAutocompleteComponent) autoCompleteComp: NgAutocompleteComponent;

  ngAfterViewInit() {
    if (this.autoCompleteComp?.searchInput?.nativeElement) {
      const inputEl = this.autoCompleteComp.searchInput.nativeElement;
      inputEl.setAttribute('autocomplete', 'new-password');
      inputEl.setAttribute('autocorrect', 'off');
      inputEl.setAttribute('autocapitalize', 'off');
    }
  }
}

方案3:兼容所有场景的兜底方案

如果上述方案都不生效,可以利用Chrome自动填充的规则,在ng-autocomplete组件前添加两个隐藏的冗余输入框,主动承接Chrome的自动填充行为,避免影响业务输入框:

<!-- 放在ng-autocomplete标签前面 -->
<input type="text" style="display: none;">
<input type="password" style="display: none;">

<ng-autocomplete
  <!-- 你原有配置保持不变 -->
></ng-autocomplete>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 00:39:02