Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 458
TSG Avatar asked Sep 19 '17 14:09

TSG


People also ask

How do you send data to a directive?

If you want to send data to directive then you should try like this: This is my custom directive, and I am going to share two value from component or HTML to the directive. You will have to use your directive in your html and send data to the directive like in below code. I am sending name and value to the test.

What is @input in Angular?

@Inoput decorator is used to pass data (property binding) from parent to child component. The component property should be annotated with @Input decorator to act as input property. Let's explore it practically. I have created an angular application which is AngApp. I have created two components.

How pass data from directive to component?

Passing data to another component is done through property binding. Property binding is used to set properties of target elements or component's @Input() decorators. The value flows from a component's property into the target element property, and you can't use it to read or pull values out of target elements.


1 Answers

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)
  }
}
like image 69
Gary Avatar answered Oct 05 '22 10:10

Gary