我正在学习 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
关于angular - 如何在angular-2中使用输入字段制作自定义指令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40419132/