angular - Angular - 限制用户不要使用不在 HTML 中的表单控件输入超过 5 个字符
问题描述
类型脚本
HTML
输出
你能帮我解决这个问题吗?
如何限制控件名称“first”不超过20个字符?
我知道如何在 HTML 中做到这一点。
是否可以限制 TS 文件中的表单控件。
请帮我找出这个。
解决方案
组件 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);
}
});
}
}
推荐阅读
- python - 如何使用 CSS 选择器来选择动态更改的类名?
- javascript - 根据AngularJS中JSON输入的下拉选择绑定数据
- k-means - 当记录和两个质心之间的欧几里德距离相同时,我应该将记录分配给哪个 k 均值集群
- c - 使用功能的重要性
- reactjs - 带有事件侦听器的错误 React useRef 钩子行为
- javascript - reactjs react dom不在元素之上
- jcenter - barteksc Android PdfViewer 在删除 jcenter() 后无法正常工作(jcenter()警告:此存储库即将关闭)
- python - Spacy Dependency Matcher 对长动词-名词短语有问题且敏感
- node.js - 我无法在本地提供 Firebase
- python - 由于 OSError 无法安装 librosa 软件包