TSG
TSG

Reputation: 4617

Pass parameter to Angular 4 directive on input

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.

Upvotes: 18

Views: 38138

Answers (4)

Eric Augusto
Eric Augusto

Reputation: 1

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.

Upvotes: 0

TSG
TSG

Reputation: 4617

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

Upvotes: 6

Gary
Gary

Reputation: 2339

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

Upvotes: 23

Chandru
Chandru

Reputation: 11184

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

Upvotes: 4

Related Questions