繁体   English   中英

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

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

我正在学习Angular-2并进行实验。 我试图用输入字段构建一个angular-2指令。 让我们来描述,我有一个名为custom.directive.ts的自定义指令:

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

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

export class InputDirective{}

现在我在这里添加一个输入字段,我想在app.component.ts中使用它。

我该怎么办?

你可以像这样声明

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);
  }
}

你可以在任何这样的元素中使用它作为属性。

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

有关详细说明,请参阅此链接

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

暂无
暂无

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

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