簡體   English   中英

Angular 4-指令中的事件監聽器不起作用

[英]Angular 4 - event listener in directive not working

我創建了一個指令,以防止用戶輸入除數字,點和逗號之外的任何字符。 但是,沒有調用當用戶輸入某些東西時應該調用的事件,並且我不明白為什么:

輸入validator.directive.ts

import { Directive, ElementRef, HostListener } from '@angular/core';

@Directive({
  selector: '[appinputvalidator]'
})
export class InputValidatorDirective {

private regex: RegExp = new RegExp('^[0-9]{1,2}([,.][0-9]{1,2})?$');

// Allow key codes for special events
// Backspace, tab, end, home
private specialKeys: Array<string> = ['Backspace', 'Tab', 'End', 'Home'];

constructor(private el: ElementRef) {
}

@HostListener('keydown', ['$event'])
onKeyDown(event: KeyboardEvent) {
    // Allow Backspace, tab, end, and home keys
    if (this.specialKeys.indexOf(event.key) !== -1) {
        return;
    }

    let current: string = this.el.nativeElement.value;
    let next: string = current.concat(event.key);
    if (next && !String(next).match(this.regex)) {
        event.preventDefault();
    }
}
  }

HTML

<td *ngIf="c.name == 'value' && typeId != 2">
<input class="form-control" 
       type="tel"  
       min="0" 
       step="1" 
       inputmode="tel" 
       appinputvalidator pattern="^[0-9]{1,2}([,.][0-9]{1,2})?$"  
       pInputText 
       [(ngModel)]="item[grid.columns[y].dataKey]" 
       id="value1-{{i}}" 
       name="value1-{{i}}" 
       (keyup)="changeItem(item, $event, i)" 
       [required]="item.remark != null ? true : false" 
       [readonly]="typeID == 0 ? true : false" />
</td>

即使將調試器放在onkeydown內,當我在瀏覽器中對其進行測試時,調試器也不會到達代碼。 怎么了?

我已經將其導入到app.module.ts

import { InputValidatorDirective } from './shared/components/inputvalidator.directive';

並將其包含在@NgModule中的“聲明”下:

    declarations: [
    AppComponent,
    HomeComponent,
    LoginComponent,
    FooterComponent,
    LeftMenuComponent,
    HeaderComponent,
    RightMenuComponent,
    ConfirmDialogComponent,
    LogoutComponent,
    InputValidatorDirective
],

Stackblitz: 點擊此處

如圖所示,您的input-validator.directive.ts位於app文件夾之外。

我已在指令模塊中編輯並導入了指令。

在此處檢查正在運行的stackblitz 該應用程序現在正在記錄keydown消息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM