属性型指令
属性型指令用于改变一个DOM元素的外观或行为。
创建属性型指令
使用命令创建一个指令类文件
ng g directive directives/highlight
创建的指令带有两个文件:
- highlight.directive.ts ```typescript import { Directive } from ‘@angular/core’;
@Directive({ // 此处的方括号表示它是css属性型选择器 // angular会自动为选择器前面加上app前缀,确保它不会和标准html属性冲突,同时也减少与第三方指令名字冲突的危险 selector: ‘[appHighlight]’ }) export class HighlightDirective {
constructor() { }
}
-hightligth.directive.spec.ts (测试文件,可删除)在根模块自动声明该指令类(若需在其他模块使用,则在其他模块中声明该指令):```typescriptimport { BrowserModule } from '@angular/platform-browser';import { AppComponent } from './app.component';// 自动引入该指令类import { HighlightDirective } from './directives/highlight.directive';@NgModule({declarations: [AppComponent,// 声明该指令类HighlightDirective],imports: [BrowserModule],providers: [],bootstrap: [AppComponent]})export class AppModule { }
修改指令类,实现带有该指令修饰的标签:鼠标移入时变黄色,鼠标移出时取消背景色
import { Directive, ElementRef, HostListener } from '@angular/core';@Directive({selector: '[appHighlight]'})export class HighlightDirective {constructor(private el: ElementRef) { }// 使用HostListener装饰器订阅当前指令所在宿主dom的事件@HostListener('mouseenter') onMouseEnter() {this.highlight('yellow');}@HostListener('mouseleave') onMouseLeave() {this.highlight(null);}private highlight(color: string) {// 通过ElementRef的nativeElement可以获取到该指令的宿主dom元素this.el.nativeElement.style.backgroundColor = color;}}
在html中使用该属性型指令:
<p appHighlight>hello world</p>
为属性型指令插入变量值
修改上面的HighlightDirective类的代码:
import { Directive, ElementRef, HostListener, Input } from '@angular/core';@Directive({selector: '[appHighlight]'})export class HighlightDirective {// 使用Input接收一个与本指令的选择器同名的变量// 因为angular会为选择器加上app前缀,所以此处最好另起一个别名@Input('appHighlight') color:string;constructor(private el: ElementRef) { }@HostListener('mouseenter') onMouseEnter() {this.highlight(this.color || 'yellow');}@HostListener('mouseleave') onMouseLeave() {this.highlight(null);}private highlight(color: string) {this.el.nativeElement.style.backgroundColor = color;}}
测试html:
<!-- 在该组件的ts中定义color变量,将color变量的值赋值为appHiglight指令 --><p [appHighlight]='color'>hello world</p>
