一. 在 Angular 中有三种类型的指令:
本章主要想介绍一下属性型指令并创建一个简单的属性型指令,属性型指令:指修改一个现有元素的外观和行为。在模板中,它们看起来就像是标准的HTML属性。
例如:ngModel指令就是属性型指令的一个例子。
二. 创建属性型指令: 首先我们的需求是创建一个指令,可以动态获取到当前元素的宽度和高度,当宽度小于一定值时,将该元素的背景色改变。
1. 创建一个size-directive.directive.ts类,内容如下:
Directive提供@Directive装饰器功能。
ElementRef注入到指令构造函数中。这样代码就可以访问到DOM元素。
Directive
装饰器函数以配置对象参数的形式,包含了指令的元数据。
@
元数据之后就是该指令的控制器类,名叫sizeDirective它包含该指令的逻辑。 然后导出Directive
sizeDirective
,以便让它能从其它组件中访问到。
import { Directive, ElementRef, HostListener } from '@angular/core';
@Directive({
selector: '[sizeDirective]'
})
export class SizeDirectiveDirective {
constructor(private el: ElementRef) {
}
@HostListener('window:load') onLoad() {
this.fixHeight();
this.fixWidth();
}
@HostListener('window:resize') onResize() {
this.fixHeight();
this.fixWidth();
}
@HostListener('mouseenter') noMouseEnter() {
this.el.nativeElement.style.backgroundColor = 'red';
}
fixHeight() {
console.log(this.el.nativeElement.clientHeight);
}
fixWidth() {
console.log(this.el.nativeElement.clientWidth);
const width = this.el.nativeElement.clientWidth;
if (width < 480) {
this.el.nativeElement.style.backgroundColor = 'yellow';
} else {
this.el.nativeElement.style.backgroundColor = 'red';
}
}
}
2. 在将该类引入到需要的模块中,例如我需要引入到app.module.ts中:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { SizeDirectiveDirective } from './size-directive.directive';
@NgModule({
declarations: [
AppComponent,
SizeDirectiveDirective
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
3. 将指令加入到所需的元素中:
<div sizeDirective>div元素</div>
最后,div的宽度或高度进行改变后,就会根据自定义的sizeDirective指令中的逻辑,将div进行样式的改变。