我已经使用管道过滤器选择器,它将限制所有特殊字符,除了-现在在输入字段中的复制粘贴期间,它会限制输入字段中的特殊字符,但在不限制特殊字符的情况下。在wildCardSearch
中,我也可以看到特殊字符。
DEMO:DEMO
用于测试:Testing#
,如果我们在输入框中粘贴,则只需要Testing
,而在显示时需要Testing#
。
我也尝试在按钮中提供选择器,但没有起作用。
TS:
public searchChange(event) {
this.wildCardSearch = event;
}
HTML:
<button type="button">{{wildCardSearch}}</button>
所有基于FormControl的控制指令扩展的基类。它将FormControl对象绑定到DOM元素
尝试一下
export class InputRestrictionDirective {
regexStr = '^[a-zA-Z0-9- ]*$';
@Input() isAlphaNumeric: boolean;
constructor(private el: ElementRef, private control : NgControl) { }
@HostListener('keydown', ['$event'])
onKeyDown(event: KeyboardEvent) {
console.log('KeyBoard');
if ( this.el.nativeElement.selectionStart === 0 && event.key === ' ' ) {
event.preventDefault();
}
if (!RegExp(this.regexStr).test(event.key)) {
event.preventDefault();
}
}
@HostListener('paste', ['$event']) blockPaste(event: KeyboardEvent) {
this.validateFields(event);
}
validateFields(event) {
setTimeout(() => {
const value = this.el.nativeElement.value.replace(/[^a-zA-Z0-9- ]/g, '').replace(/\s/g, '');
this.control.control.setValue(value);
event.preventDefault();
}, 100)
}
}
Forked Example
在模板中,将模板Ref变量提供给您的输入#inputValue
<div class="d-flex">
<input type="text" class="form-control min-w300" placeholder="Search Agent" [(ngModel)]="wildCardSearch" (ngModelChange)="searchChange($event)" appInputRestriction #inputValue>
</div>
在.ts中使用setTimeout
@ViewChild('inputValue',{static : false}) el:ElementRef; public searchChange(event) { setTimeout(() => { this.wildCardSearch = this.el.nativeElement.value }, 100) }