首页 > 解决方案 > 仅用于字母字符的输入掩码仅允许 1 个单词在 Angular 中使用 Primeng

问题描述

就像教程说的“ a - Alpha character (defaut: A-Z,a-z)”没关系。

但是当我mask="a"像下面这样申请时,只让我输入 1 个单词,但我不想限制输入的大小。所以人们可以输入任何大小的单词。我怎样才能做到这一点?

我尝试使用characterPattern="[А-Zа-z]"或提供具有常规表达式的普通 html 模式属性,^[A-Za-z]但没有工作。提前致谢

<p-inputMask mask="a" [placeholder]="'gerekli' | translate" [(ngModel)]="User.adi"></p-inputMask>

标签: htmlangularprimeng

解决方案


您可以执行以下操作,

在您的 component.ts 文件中,

setInputFilter(inputHTML, inputValue) {
    [
      "input",
      "keyup",
      "keydown",
      "mouseup",
      "mousedown",
      "select",
      "contextmenu",
      "drop"
    ].forEach(function(event) {
      inputHTML.addEventListener(event, function() {
        if (inputValue(this.value)) {
          this.previousValue = this.value;
          this.previousSelectionStart = this.selectionStart;
          this.previousSelectionEnd = this.selectionEnd;
        } else if (this.hasOwnProperty("previousValue")) {
          this.value = this.previousValue;
        }
      });
    });
  }

setInputFilterAfterViewInit生命周期钩子中调用函数。

ngAfterViewInit() {

    this.setInputFilter(document.getElementById("inputText"), function (value) {

      return /^[a-zA-Z]*$/.test(value);

    })
  }

在您的 component.html 文件中,

<input id="inputText" pInputText [(ngModel)]="val"/>

我正在使用InputTextModulePrimeNG 而不是InputMaskModule


推荐阅读