首页 > 解决方案 > Angular - 限制用户不要使用不在 HTML 中的表单控件输入超过 5 个字符

问题描述

类型脚本

在此处输入图像描述

HTML

在此处输入图像描述

输出

在此处输入图像描述

你能帮我解决这个问题吗?

如何限制控件名称“first”不超过20个字符?

我知道如何在 HTML 中做到这一点。

是否可以限制 TS 文件中的表单控件。

请帮我找出这个。

标签: angular

解决方案


组件 HTML 文件

<div>
  <h3>My Restricted Control</h3>
  <input type="text" [formControl]="restrictedInputControl">
</div>

组件 TS 文件

export class AppComponent {
  restrictedInputControl: FormControl = new FormControl('', [Validators.minLength(5)]);
  allowedCharacters = 'abcdefgh'; // Anything not included in this string will be removed

  constructor() {
    // We subscribe to every change ocurring to this FormControl
    this.restrictedInputControl.valueChanges.subscribe(newInput => {
      // Get the last user input
      const lastEntry = newInput.split('')[newInput.length - 1];

      // Check if the last input character is in allowedCharacters
      if (!this.allowedCharacters.split('').includes(lastEntry)) {

        // If it doesn't exist in allowed ones we Patch the FormControl value with the forbidden character sliced from current value;
        const valueWOLastInput: string = this.restrictedInputControl.value.slice(0, this.restrictedInputControl.value.length - 1);
        this.restrictedInputControl.patchValue(valueWOLastInput);
      }
    });
  }
}

推荐阅读