文章参考
属性指令
指令创建
ng g directive hbFontcolor
案例
指令的代码逻辑
import { Directive, ElementRef, HostListener, Input } from '@angular/core';
@Directive({
selector: '[appHbBackground]'
})
export class HbBackgroundDirective {
constructor(private el: ElementRef) {
this.el = el;
}
@Input('appHbBackground') bgColor: string;
@HostListener('mouseenter') onMouseEnter() {
this.highlight(this.bgColor || 'red');
}
@HostListener('mouseleave') onMouseLeave() {
this.highlight(null);
}
private highlight(color: string) {
this.el.nativeElement.style.backgroundColor = color;
}
}
在NgModule中declarations声明
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
import { HbModuleModule } from '../moduleHb/hb-module/hb-module.module'
import { AppComponent } from './app.component';
import { HeaderComponent } from './page/header/header.component';
import { NewsComponent } from './page/news/news.component';
import {StorageService} from './page/service/storage.service'
import { AppRoutingModule } from './router/app-routing.module';
import { HttpdemoComponent } from './page/httpdemo/httpdemo.component';
import { StrLengthPipe } from './pipeCustomer/str-length.pipe';
import { HbFontcolorDirective } from './directiveCustomer/hb-fontcolor.directive';
import { HbBackgroundDirective } from './directiveCustomer/hb-background.directive';
@NgModule({
declarations: [
AppComponent,
HeaderComponent,
NewsComponent,
HttpdemoComponent,
StrLengthPipe,
HbFontcolorDirective,
HbBackgroundDirective
],
imports: [
BrowserModule,
HttpClientModule,
FormsModule,
AppRoutingModule,
HbModuleModule
],
providers: [
StorageService
],
bootstrap: [AppComponent]
})
export class AppModule { }