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

问题描述 投票:3回答:1

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

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

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

export class InputDirective{}

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

我该怎么办?

angular angular2-directives
1个回答
-4
投票

你可以像这样声明

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

© www.soinside.com 2019 - 2024. All rights reserved.