Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send input data value into custom directive in angular-2?

I am experimenting upon custom directives of angular-2 basic where I want to parse an input value in my custom directive.

Lets have a look.

I have an app component called app.component.ts. Where I have taken an input field.

<input [(ngModel)] = "myInput"/> 

Next I build a custom directive name custom.directive.ts

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

@Directive ({
  selector : '[customDir]'
})
export class CustomDirective{
  constructor(private el : ElementRef, private renderer: Renderer){ }
}

Now I would like to input anything in "app.component.ts and parse it in my custom directive by which I can simply print it in console..

Lets re modify my code...

<app.component.ts>
<input [(ngModel)] = "myInput" [customDir] = "myInput"/> 
<custom.directive.ts>
import { Directive, ElementRef, Renderer, Input} from '@angular/core';

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

export class CustomDirective{
  @Input('customDir') myInput : any;
  constructor(private el : ElementRef, private renderer: Renderer){ }
     console.log(this.myInput);
  }

But it is not working properly. Printing un define..

My Concern is...

1... How I parse the data just against the each key press..?

Please suggest me anyone...

like image 348
R. Dey Avatar asked Oct 18 '22 23:10

R. Dey


1 Answers

@Directive ({
  selector : '[customDir]',
  exportAs: 'customDir' // <<<=== added
})
export class CustomDirective{
  myInput : any;
}

and use it like

<input customDir #customDir="customDir" [(ngModel)]="myInputInApp" (ngModelChange)="customDir.myInput = $event"/> 

The first customDir is to get the directive applied at all.

#customDir="customDir" is to create a template variable that has a reference to the directive (requires exportAs)

[(ngModel)]="customDir.myInput" binds to the directive referenced by the template variable #customDir and its property input. @Input() is not required for this case because it's not Angular binding that is used here.

Plunker example

This should work as well and is easier to use:

@Directive ({
  selector : '[customDir]',
})
export class CustomDirective{

  @HostListener('ngModelChange', ['$event'])
  onModelChange(event) {
    console.log(event);
  }
}
<input customDir [(ngModel)]="someOtherProp"/> 

Plunker example

like image 147
Günter Zöchbauer Avatar answered Nov 17 '22 05:11

Günter Zöchbauer