2

I have this custom directive I'm setting up like so..

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

@Directive({
    selector: '[pieceRate]'
})
export class PieceRateDirective {
    @HostListener('input', ['$event'])
    @Input() dollarMax: string;
    @Input() centMax: string;
    onkeydown(event: KeyboardEvent) {
      const input = event.target as HTMLInputElement;
      console.log(this.dollarMax);
      console.log(this.centMax);
  }
}

I have it imported in a shared module that gets imported into my main module so..

Shared Module

import { PieceRateDirective} from '@app/directives...'
...

@NgModule({
   imports..
   declarations: [
     PieceRateDirective
   ],
   exports: [
      PieceRateDirective
   ]
})

Main Module

import { SharedModule } from '@app/shared.module';
...

@NgModule({
   imports: [
      SharedModule
   ]
})
...

So that all appears to be working fine, but when I actually try and use my directive like so..

<input
   pieceRate
   [dollarMax]="rangeTo?.toString().split('.')[0]"
   [(ngModel)]="dollarPieceRate"
   type="number" >

and type in a number i get this error

TypeError: jit_nodeValue_10(...).dollarMax is not a function

I'm not sure what could be causing this issue..

Any help would be appreciated!

2
  • 1
    Try moving the two @Input lines above the @HostListener (which should be followed immediately by onKeyDown). Commented Oct 16, 2018 at 0:15
  • grrrr I just spent 5 mins working that out lol ... glad you fixed it Commented Oct 16, 2018 at 0:22

2 Answers 2

1

The @HostListener decorator is used the associate a handler to an event. In the present case, the declaration of onkeydown should follow immediately the decorator:

export class PieceRateDirective {

  @Input() dollarMax: string;
  @Input() centMax: string;

  @HostListener('input', ['$event'])
  onkeydown(event: KeyboardEvent) {
    ...
  }
}
Sign up to request clarification or add additional context in comments.

Comments

0

You have to apply the host listener to the function and not the input string.

export class PieceRateDirective {
  @Input() dollarMax: string;
  @Input() centMax: string;

  @HostListener('input', ['$event'])
  onkeydown(event: KeyboardEvent) {
    const input = event.target as HTMLInputElement;
    console.log(this.dollarMax);
    console.log(this.centMax);
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.