typescript Angular 10 Reactive Form -限制用户输入字段中的字符数

r3i60tvu  于 2023-06-30  发布在  TypeScript
关注(0)|答案(2)|浏览(125)

我正在构建一个Angular 10React式表单,并希望限制用户可以在输入字段中输入的字符数。maxLength Validator并不阻止用户输入更多的字符-表单只是变得无效。如果用户已达到字符数限制,则输入字段中不应再显示字符。我正在使用表单生成器:

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>

有没有人知道如何做到这一点?

pdsfdshx

pdsfdshx1#

您可以使用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>
brqmpdu1

brqmpdu12#

我建议你写一个指令,防止键下降。

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

@Directive({
  selector: "[appMaxLength]"
})
export class MaxLengthDirective {
  @Input() appMaxLength;
  el:any;
  constructor(el:ElementRef) {
    this.el = el;
  }

  @HostListener("paste", ["$event"]) onPaste(event){
   setTimeout(()=>{
    const value = this.el.nativeElement.value;
    const maxLength = parseInt(this.appMaxLength);
    if (value.length > maxLength -1) {
        this.el.nativeElement.value = value.substring(0, (maxLength));
    }
   })
    
  }

  @HostListener("keydown", ["$event"]) onKeydown(event) {
    const value = this.el.nativeElement.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(keyCodeIndex != -1){
      return;
    }
    if (value.length > maxLength -1) {
      event.preventDefault();
      event.stopPropagation();
    }
  }
}

要获取键码列表:https://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes
工作示例:https://stackblitz.com/edit/angular-ivy-34djqh
使用Keycode Index的工作示例:https://stackblitz.com/edit/angular-ivy-vgsrx5
粘贴功能的工作示例:https://stackblitz.com/edit/angular-ivy-xeei1m

相关问题