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.

4 Answers 4

23

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)
  }
}
4
  • 2
    I think that format is depricated, but I used @Input('inputTextFilter') params: string; and params is undefined
    – TSG
    Commented Sep 19, 2017 at 14:29
  • Where did you try to fetch params and is it defined in the first place in the input tag
    – Gary
    Commented Sep 19, 2017 at 14:32
  • It still prints Undefined
    – TSG
    Commented Sep 19, 2017 at 14:56
  • 4
    [inputTextFilter]="A" if A i a variable and inputTextFilter="A" if "A" is a string
    – Gary
    Commented Sep 19, 2017 at 15:34
6

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'"

1
  • @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
    Commented Sep 19, 2017 at 15:33
4

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);
    }
}
1
  • I've added my directive code in the original question. Looks almost identical to what you have, but params is always undefined.
    – TSG
    Commented Sep 19, 2017 at 14:39
0

In case anyone is still getting undefined inside the directive after following the accepted awnser, be sure that you're trying to access the variable inside ngOnInit not on the constructor.

The constructor of the directive is called before Angular initializes the directive's inputs.

1

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.