简体   繁体   中英

Angular 4 - event listener in directive not working

I've created a directive that prevents users from entering any characters except numbers, dot and comma. However, the event that should be called when user inputs something is not called and I don't understand why:

input-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>

Even if I put debugger inside the onkeydown, it doesn't reach the code when I test it in browser. What's wrong?

I've imported it to app.module.ts like this

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

and also included it in @NgModule under "declarations":

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

Stackblitz: CLICK HERE

As seen in the image, your input-validator.directive.ts was outside the app folder.

I have edited and imported the directive in the app module.

Check the running stackblitz here. The app is now logging the keydown message.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM