在 Angular 中有三种类型的指令:
组件 — 拥有模板的指令
结构型指令 — 通过添加和移除 DOM 元素改变 DOM 布局的指令
属性型指令 — 改变元素、组件或其它指令的外观和行为的指令。
属性型指令:
1.初始化
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent {
color: string; //声明变量color,页面绑定的变量
}
2.声明指令
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { HighlightDirective } from './highlight.directive'; //引入插件
@NgModule({
imports: [ BrowserModule ],
declarations: [
AppComponent,
HighlightDirective//引入插件
],
bootstrap: [ AppComponent ]
})
export class AppModule { }
3.创建指令
/* tslint:disable:member-ordering */
import { Directive, ElementRef, HostListener, Input } from '@angular/core';
@Directive({
selector: '[appHighlight]'//css属性选择器
})
export class HighlightDirective {
constructor(private el: ElementRef) { }
@Input() defaultColor: string; //声明属性
@Input('appHighlight') highlightColor: string;//声明属性别名appHighlight
@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;
}
}
4.调用指令
My First Attribute Directive
Pick a highlight color
Green
Yellow
Cyan
Highlight me!
Highlight me too!
结构型指令
一个元素上只能放一个结构型指令
创建步骤:
1.导入 Directive 装饰器(而不再是 Component)。
2.导入符号 Input、TemplateRef 和 ViewContainerRef,你在任何结构型指令中都会需要它们。
3.给指令类添加装饰器。
4.设置 CSS 属性选择器 ,以便在模板中标识出这个指令该应用于哪个元素。
1.创建组件
import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';
@Directive({ selector: '[appUnless]'}) //用属性设置样式
export class UnlessDirective {
private hasView = false;
constructor(
private templateRef: TemplateRef
private viewContainer: ViewContainerRef) { } //组件的容器
@Input() set appUnless(condition: boolean) {
if (!condition && !this.hasView) {
this.viewContainer.createEmbeddedView(this.templateRef); //放入容器中
this.hasView = true;
} else if (condition && this.hasView) {
this.viewContainer.clear(); //销毁本容器中的所有视图
this.hasView = false;
}
}
}
2.初始化
import { UnlessDirective } from './unless.directive';
@NgModule({
imports: [ BrowserModule, FormsModule ],
declarations: [
AppComponent,
UnlessDirective
],
bootstrap: [ AppComponent ]
})
export class AppModule { }
3.页面调用
Show this sentence unless the condition is true.
你可以根据属性名在绑定中出现的位置来判定是否要加 @Input。
当它出现在等号右侧的模板表达式中时,它属于模板所在的组件,不需要 @Input 装饰器。
当它出现在等号左边的方括号([ ])中时,该属性属于其它组件或指令,它必须带有 @Input 装饰器。