Pass parameter to Angular 4 directive on input

TSG picture TSG · Sep 19, 2017 · Viewed 17.4k times · Source

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.

Answer

Gary picture Gary · Sep 19, 2017

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