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?

1
  • Your Query does not describe what exactly you wanted to achieve from custom directive. Please click Here for one of the example to demostrate the use of directive. Commented Apr 29, 2019 at 13:52

1 Answer 1

-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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.