简体   繁体   中英

How to make a custom directive with input field in angular-2?

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM