我正在学习Angular-2并对其进行实验。我正在尝试构建一个带有输入字段的angular-2指令。让我们来描述一下,我有一个名为custom.directive.ts的自定义指令
import { Directive } from '@angular/core';
@Directive({
selector: '[inputDir]',
})
export class InputDirective{}现在我在这里添加了一个输入字段,我想在我的app.component.ts中使用它。
我该怎么做呢?
发布于 2016-11-05 01:51:28
您可以像这样声明
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
https://stackoverflow.com/questions/40419132
复制相似问题