【问题标题】:Globally turn off autocomplete on material's matInput全局关闭材料 matInput 的自动完成功能
【发布时间】:2019-12-12 08:29:01
【问题描述】:

有没有办法全局关闭材料的MatInput 字段的自动完成行为?我想摆脱这种到处重复的样板代码:

<input matInput formControlName="myCtrl" autocomplete="off" />

例如类似于在应用模块的提供程序数组中使用注入令牌全局定义表单字段的外观和标签选项:

// Default appearance of material form fields
{ provide: MAT_FORM_FIELD_DEFAULT_OPTIONS, useValue: { appearance: 'fill' } },
// Globally disable label of material form fields
{ provide: MAT_LABEL_GLOBAL_OPTIONS, useValue: { float: 'never' } }

我扫描了文档和源代码,但找不到任何东西。

【问题讨论】:

  • 我不认为有这样的选择。有一个MAT_AUTOCOMPLETE_DEFAULT_OPTIONS 令牌,但没有禁用它的选项。您可以尝试使用全局脚本
  • 这是我的担心。你有这样一个全球脚本黑客的来源吗?
  • 我们可以在form标签上使用autocomplete="off",而不是将其添加到所有输入元素中吗?

标签: angular angular-material


【解决方案1】:

有点晚了,但也许会有帮助。

你可以添加这个简单的指令:

import { Directive, HostBinding, Attribute } from '@angular/core';

@Directive({
  selector: '[matInput]',
})
export class AutocompleteOffDirective {

  @HostBinding('attr.autocomplete') auto;
  constructor(@Attribute('autocomplete') autocomplete: string) {
    this.auto = autocomplete || 'off'
  }

}

如果您选择覆盖自动完成属性,它将从元素中获取文本。

【讨论】:

  • 记得将此指令添加到 app.module.ts 或其他一些模块以启用它
【解决方案2】:

正如我在评论中所说,如果没有更好的解决方案,您可以添加一个全局脚本,将 autocomplete="off" 设置为您的所有 matInput 元素。

例如,您可以在 polyfills.ts 文件中添加这个 sn-p:

document.addEventListener('DOMContentLoaded', () => {

  Array.from(document.querySelectorAll('input[matInput]'))
    .forEach(element => {
      element.setAttribute('autocomplete', 'off');
    });

});

注意:考虑将箭头函数转换为普通函数以支持 IE11

【讨论】:

  • 当 DOM 改变时监听器不会被触发。我尝试了MutationObserver,但它真的会扼杀任何性能,因为当我观察身体的变化时它几乎无休止地被解雇......所以,我认为这不值得麻烦。
  • @sl3dg3 你是对的,这不考虑*ngIf的东西
猜你喜欢
  • 1970-01-01
  • 2020-01-29
  • 2020-09-05
  • 2017-08-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多