Angular 10反应形式-用户输入字段中的字符数限制

问题描述

我正在构建Angular 10反应形式,并希望限制用户可以在输入字段中输入的字符数。 maxLength验证程序不会阻止用户输入更多字符-表单只会变得无效。如果用户已达到字符数限制,则不应在输入字段中出现更多字符。我正在使用表单生成器:

profileForm = this.fb.group({
  name: ['',[Validators.required,Validators.maxLength(10)]],});


<form [formGroup]="profileForm">
  <label>
    Name:
    <input type="text" formControlName="name" required />
  </label>
  <button type="submit" [disabled]="!profileForm.valid">Submit</button>
</form>

有人知道怎么做吗?

解决方法

我建议您编写一条防止按键按下的指令。

   import { Directive,HostListener,Input } from "@angular/core";

@Directive({
  selector: "[appMaxLength]"
})
export class MaxLengthDirective {
  @Input() appMaxLength;
  constructor() {}

  @HostListener("keydown",["$event"]) onKeydown(event) {
    const value = event.target.value;
    const maxLength = parseInt(this.appMaxLength);
    const keycode = event.which || event.keycode;
    const allowedKeycodes = [8,13,46,37,38,39,40]
    const keyCodeIndex = allowedKeycodes.indexOf(keycode);
    if ((value.length > maxLength -1) && (keyCodeIndex === -1)) {
      event.preventDefault();
      event.stopPropagation();
    }
  }
}

要获取键码列表:https://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes

工作示例:https://stackblitz.com/edit/angular-ivy-34djqh

,

您可以使用maxlength HTML属性来限制文本输入中的字符数。

<form [formGroup]="profileForm">
  <label>
    Name:
    <input type="text" formControlName="name" maxlength="10" required />
  </label>
  <button type="submit" [disabled]="!profileForm.valid">Submit</button>
</form>