[英]Event handler performance issue in Angular 4 / 5
很抱歉,如果我的問題很愚蠢,但我們的申請中遇到了延遲問題。 KEYPRESS事件處理程序是罪魁禍首。 我們在整個應用程序中使用以下指令。 它通過HostListener
檢查KeyPress
。 按下該鍵時,該指令使用regexp檢查該值,如果condition為false,則執行preventDefault
。
private regexMap = { // add your own
'999': /^([0-9]){0,3}$/g,
'9999': /^([0-9]){0,4}$/g,
...
...
}
@HostListener('keypress', [ '$event' ])
public nInput(event: KeyboardEvent) {
// Allow Backspace, tab, end, and home keys
if (this.specialKeys.indexOf(event.key) !== -1) {
return;
}
this.pattern = this.regexMap[this.validationFormat];
const current: string = this.el.nativeElement.value;
const next: string = current.concat(event.key);
if (next && !String(next).match(this.pattern)) {
event.preventDefault();
}
}
我不知道如何解決這個問題。 debounceTime
解決這個問題嗎? 我不知道如何為這種方法添加去抖動。 請有人幫我解決這個問題。
修復了DebounceTime的問題:)只是在幫助主題中增加了去抖時間。 基本上當用戶輸入內容時它停止所有操作,然后將EVENT(按鍵值)發送到SUBJECT並在主題中去抖時間等待300ms然后再進行功能測試
private keyPressed = new Subject();
private subscription: Subscription;
private pattern: RegExp;
private regexMap = { // add your own
'999': /^([0-9]){0,3}$/g,
'9999': /^([0-9]){0,4}$/g,
...
...
}
private specialKeys: string[] = ['Backspace', 'Tab', 'End', 'Home'];
constructor(private el: ElementRef) {
}
public ngOnInit() {
this.subscription = this.keyPressed.pipe(debounceTime(300)).subscribe(
(event) => this.checkRegExpression(event)
);
}
public ngOnDestroy() {
this.subscription.unsubscribe();
}
@HostListener('keypress', ['$event']) public nInput(event: KeyboardEvent) {
event.preventDefault();
event.stopPropagation();
this.keyPressed.next(event);
}
private checkRegExpression(event) {
if (this.specialKeys.indexOf(event.key) !== -1) {
return;
}
this.pattern = this.regexMap[this.validationFormat];
const current: string = this.el.nativeElement.value;
const next: string = current.concat(event.key);
if (next && !String(next).match(this.pattern)) {
event.preventDefault();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.