angular6自定义属性指令

文章参考

属性指令

指令创建

ng g directive hbFontcolor

案例

指令的代码逻辑

import { Directive, ElementRef, HostListener, Input } from '@angular/core';

@Directive({
  // 使用CSS选择器,如果属性中有appHbBackground,就表示使用了该主键
  selector: '[appHbBackground]'
})
export class HbBackgroundDirective {

  // 使用依赖注入的方式,el 代表使用指令的控件
  constructor(private el: ElementRef) { 
    this.el = el;
  }

   // 接收属性 appHbBackground的值,并且将值传递给bgColor变量
  @Input('appHbBackground') bgColor: string;

  // 给使用指令的控件添加 mouseenter的事件
  @HostListener('mouseenter') onMouseEnter() {
    this.highlight(this.bgColor || 'red');
  }

  @HostListener('mouseleave') onMouseLeave() {
    this.highlight(null);
  }

  private highlight(color: string) {
      // this.el.nativeElement 指原生的html控件
      this.el.nativeElement.style.backgroundColor = color;
  }
}

在NgModule中declarations声明

/**
 * 告诉angular 如何组装应用
 */
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 装饰器将AppModule标记为Angular 模块类(也叫做 NgModule类)
// @NgModule 接收一个元数据对象,告诉Angular 如何编译和启动应用
@NgModule({
  // 该模块的 declarations 数组告诉 Angular 哪些组件属于该模块
  // 该应用所拥有的组件——组件、管道、指令
  declarations: [
    AppComponent,
    HeaderComponent,
    NewsComponent,
    HttpdemoComponent,
    StrLengthPipe,
    HbFontcolorDirective,
    HbBackgroundDirective
  ],
  // 当前项目依赖哪些模块
  imports: [
    BrowserModule,
    HttpClientModule,
    // 如果要引入双向绑定,则需要引入FormModule
    FormsModule,
    AppRoutingModule,
    // 自定义模块
    HbModuleModule
  ],
  // 各种服务提供商——定义服务
  providers: [
    StorageService
  ],
  // 默认启动哪个组件——根组件
  bootstrap: [AppComponent]
})

// 根模块不需要导出任何东西,因为其他组件不需要导入根模块,但是一定要写
export class AppModule { }

猜你喜欢

转载自blog.csdn.net/hbiao68/article/details/84563186
今日推荐