首先看官网的:
/* tslint:disable:member-ordering */
import { Directive, ElementRef, HostListener, Input } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
constructor(private el: ElementRef) { }
@Input() defaultColor: string;
@Input('appHighlight') highlightColor: string;
@HostListener('mouseenter') onMouseEnter() {
this.highlight(this.highlightColor || this.defaultColor || 'red');
}
@HostListener('mouseleave') onMouseLeave() {
this.highlight(null);
}
private highlight(color: string) {
this.el.nativeElement.style.backgroundColor = color;
}
}
自己模仿的
一个input 在 输入的时候,进行检测
新建 verifyMaterial.directive.ts文件
import
{ Directive
, ElementRef
, HostListener
, Input
}
from
'@angular/core'
;
@Directive
({
selector
:
'[appVerifyMaterial]'
})
export
class VerifyMaterialDirective
{
constructor
(
private el
: ElementRef
)
{
}
@Input
(
'appVerifyMaterial'
) inputMaterial
:
string
;
@Input
() fontColor
:
string
;
@HostListener
(
'ngModelChange'
) ngModelChange
()
{
this
.el
.nativeElement
.style
.color
=
this
.fontColor
;
console
.log
(
this
.el
.nativeElement
.value
);
// console.log(this.inputMaterial);
}
private highlight
(color
:
string
)
{
this
.el
.nativeElement
.style
.backgroundColor
= color
;
}
}
app.module.ts 引入
import
{ VerifyMaterialDirective
}
from
'./verifyMaterial.directive'
;
效果图: