angular特殊字符指令
2024-12-17 本文已影响0人
姜治宇
对于输入文本框,经常会有过滤特殊字符的要求,这个可以封装指令来解决。
import { Directive, ElementRef, HostListener } from '@angular/core';
import { NgControl } from '@angular/forms';
@Directive({
selector: '[appFilterSpecialChar]'
})
export class FilterSpecialCharDirective {
private specialStringRegexp = /[`~!@#$%^&*()+|{}\[\]:;'"<>?,.\/\\]/g;
private isComposing = false;
private curVal:any;
constructor(private ngControl: NgControl,private el:ElementRef) {}
ngOnInit(){
const ctrl = this.ngControl.control;
if(!ctrl)
return;
this.el.nativeElement.addEventListener('compositionstart',()=>{
this.isComposing = true;
});
this.el.nativeElement.addEventListener('compositionend',()=>{
this.isComposing = false;
});
ctrl.valueChanges.subscribe(v=>{
if(!v || this.isComposing){
return;
}
console.log('过滤前的字符>>>',v);
this.curVal = v;
this.cleanValue();
});
}
private cleanValue(){
const ctrl = this.ngControl.control;
if(ctrl){
const filteredValue = this.curVal.replace(this.specialStringRegexp,'');
console.log('过滤后的字符>>>',filteredValue);
ctrl.setValue(filteredValue, { emitEvent: false });
}
}
ngOnDestroy(){
this.el.nativeElement.removeEventListener('compositionstart',()=>{
this.isComposing = true;
});
this.el.nativeElement.removeEventListener('compositionend',()=>{
this.isComposing = false;
this.cleanValue();
});
}
//这样写会出现打汉字时,来不及拼出汉字就把拼音显示上去了
// @HostListener('input', ['$event'])
// onInput(event: Event): void {
// console.log('filter spec>>>',event);
// const input = event.target as HTMLInputElement;
// const filteredValue = input.value.replace(this.specialStringRegexp, '');
// this.ngControl.control?.setValue(filteredValue, { emitEvent: false });
// }
}
指令主要用于封装对DOM的操作和行为,它们可以被附加到HTML元素、组件或属性上,用于低级别的DOM操作,如样式应用、事件监听、属性绑定等。
这里需要注意的是,如果直接监听input输入行为,会导致拼音输入法有问题,用户来不及拼出汉字就回显了,所以得用到compositionstart和compositionend事件。
当用户开始输入拼音时,触发compositionstart事件,此时可以设置一个状态标记表示正在输入法组合中。
当用户完成输入汉字后,触发compositionend事件,此时可以取消状态标记,并进行相应的处理。
然后在模块里面导入:
import { FilterSpecialCharDirective } from '../../directive/filter-special-char.directive';
import { SuffixInputComponent } from './suffix-input/suffix-input.component';
@NgModule({
declarations: [
FilterSpecialCharDirective,
SuffixInputComponent
],
imports: [
...
],
exports: [],
})
export class TestModule {}
这样就可以在前端使用了:
<input
appFilterSpecialChar
type="text"
nz-input
[placeholder]="text"
[(ngModel)]="keyword"
(keyup.enter)="onSearch()"
(ngModelChange)="trimValue($event)"
/>