简体   繁体   English

如何使用angular-2中的输入字段创建自定义指令?

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

I am learning Angular-2 and experimenting on it. 我正在学习Angular-2并进行实验。 I was trying to build an angular-2 directive with an input field. 我试图用输入字段构建一个angular-2指令。 Lets describe, I have a custom directive called custom.directive.ts : 让我们来描述,我有一个名为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. 现在我在这里添加一个输入字段,我想在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 https://angular.io/docs/ts/latest/guide/attribute-directives.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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