Smokey Dawson
Smokey Dawson

Reputation: 9230

Custom Directive Inputs returning error Angular 5

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!

Upvotes: 2

Views: 236

Answers (2)

Martin Parenteau
Martin Parenteau

Reputation: 73731

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) {
    ...
  }
}

Upvotes: 1

Avin Kavish
Avin Kavish

Reputation: 8937

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);
  }
}

Upvotes: 0

Related Questions