4

I am learning Angular-2 and experimenting on it. I was trying to build an angular-2 directive with an input field. Lets describe, I have a custom directive called custom.directive.ts:

import { Directive } from '@angular/core';

@Directive({
    selector: '[inputDir]',    
})

export class InputDirective{}

Now I add here an input field, which I would like to use in my app.component.ts.

How may I do it?

Samuel Philipp
  • 10,631
  • 12
  • 36
  • 56
R. Dey
  • 509
  • 2
  • 7
  • 19
  • Your Query does not describe what exactly you wanted to achieve from custom directive. Please click [Here](https://stackoverflow.com/questions/41465542/angular2-input-field-to-accept-only-numbers) for one of the example to demostrate the use of directive. – Mukesh Rathore Apr 29 '19 at 13:52

1 Answers1

-3

You can declare like this

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

@Directive({
  selector: '[myHighlight]'
})
export class HighlightDirective {
  private _defaultColor = 'red';

  constructor(private el: ElementRef, private renderer: Renderer) { }

  @Input('myHighlight') highlightColor: string;

  @HostListener('mouseenter') onMouseEnter() {
    this.highlight(this.highlightColor || this._defaultColor);
  }
  @HostListener('mouseleave') onMouseLeave() {
    this.highlight(null);
  }

  private highlight(color: string) {
    this.renderer.setElementStyle(this.el.nativeElement, 'backgroundColor', color);
  }
}

and you can use this as attribute in any element like this.

<p [myHighlight]="color">Highlight me!</p>

Please do refer this link for details explanation

https://angular.io/docs/ts/latest/guide/attribute-directives.html