18

I have an input text field like this

<input type="text" class="form-control"  [inputTextFilter]="A" [ngModel]="name">

and my directive is:

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

@Directive({
  selector: '[inputTextFilter]'
})

export class InputTextFilterDirective {
  @Input('inputTextFilter') params: string;

  @HostListener('keypress', ['$event'])
  onKeyUp(event: KeyboardEvent) {
    console.log('got parameters: '+this.params);
  }
}

and I have created a Directive called "inputTextFilter" to which I want to pass the "A" parameter. My passed parameter always shows as undefined.

TSG
  • 4,242
  • 9
  • 61
  • 121

3 Answers3

22

Try this.

Update:

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

@Directive({
  selector: '[inputTextFilter]'
})
export class MyDirective {
  @Input('inputTextFilter') params: string;
  constructor(){}
  ngOnInit(){
     console.log(this.params)
  }
}
Community
  • 1
  • 1
Gary
  • 2,293
  • 2
  • 25
  • 47
5

In the hope that this helps someone else...the problem is in the template.

When I pass the input as [myDirective]="A" the A is being intpreted as an undefined variable. Since I wanted to pass the letter A I should have said [myDirective]="'A'"

TSG
  • 4,242
  • 9
  • 61
  • 121
  • @yurzui Please mark this as the answer. I would want to upvote it. Seems like it was all a working code and TSG is sending string into directive rather than a variable – Gary Sep 19 '17 at 15:33
3

Try like this in directive :

import {Directive, Input, ElementRef} from 'angular2/core';
@Directive({
    selector: '[inputTextFilter]'
})
class FocusDirective {
    @Input() inputTextFilter: any;
    protected ngOnChanges() {
         console.log('inputTextFilter', this.inputTextFilter);
    }
}
Chandru
  • 10,864
  • 6
  • 38
  • 53
  • I've added my directive code in the original question. Looks almost identical to what you have, but params is always undefined. – TSG Sep 19 '17 at 14:39