1 自定概述
2 自定义指令
详情参见《揭秘Angular2》
2.1 属性指令
》工具代码
<div class="panel panel-primary"> <div class="panel-heading"> <ng-content select=".heading"></ng-content> </div> <div class="panel-body"> <ng-content select=".body"></ng-content> </div> <div class="panel-footer"> {{currentDate | date : "yyyy-MM-dd HH:mm:ss"}} </div> </div>
import { Component, OnInit } from '@angular/core';
import { setInterval } from 'timers';
@Component({
selector: 'panel',
templateUrl: './panel.component.html',
styleUrls: ['./panel.component.scss']
})
export class PanelComponent implements OnInit {
currentDate : Date;
constructor() { }
ngOnInit() {
this.currentDate = new Date();
setInterval(() => {
this.currentDate = new Date();
}, 1000);
}
}
》指令代码
import { Directive, Input, ElementRef, HostListener } from '@angular/core';
@Directive({
selector: '[appMyHighLight]'
})
export class MyHighLightDirective {
@Input()
highlightColor : string;
constructor(
private _elementRef : ElementRef // 依赖注入:ElementRef对象用来操作DOM节点
) { }
@HostListener("mouseenter") // 监听鼠标移入事件
onMouseEnter() {
this.highlight(this.highlightColor);
}
@HostListener("mouseleave") // 监听鼠标移除事件
onmouseleave() {
this.highlight(null);
}
// 利用 ElementRef 修改DOM
private highlight(color : string) {
this._elementRef.nativeElement.style.backgroundColor = color;
}
}
》应用指令的组件
<panel> <div class="heading"> 测试组件01 </div> <div appMyHighLight highlightColor="#ff3300" class="body"> <p>重庆是个好地方</p> </div> </panel>
import { Component, OnInit } from '@angular/core';
import { TestService } from '../services/test.service';
@Component({
selector: 'test01',
templateUrl: './test01.component.html',
styleUrls: ['./test01.component.scss']
})
export class Test01Component implements OnInit {
constructor(
) { }
ngOnInit() {
}
onClick() : void {
// 将对象转化成JSON字符串并存储道浏览器缓存中
window.localStorage.setItem("user", JSON.stringify({name: "王杨帅", age: 9}));
}
}
2.2 结构性指令
》指令代码
import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core'; @Directive({ selector: '[appDelay]' }) export class DelayDirective { constructor( private templateRef: TemplateRef<any>, private viewContainerRef: ViewContainerRef ) { } @Input() set appDelay(time: number) { setTimeout(() => { this.viewContainerRef.createEmbeddedView(this.templateRef); }, time); } }
》应用指令的组件
<panel> <div class="heading"> 测试组件02 </div> <div class="body"> <div *ngFor="let item of [1,2,3]"> <span *appDelay="500 * item"> 第 {{item}} 张卡片 </span> </div> </div> </panel>
import { Component, OnInit } from '@angular/core';
import { TestService } from '../services/test.service';
@Component({
selector: 'test02',
templateUrl: './test02.component.html',
styleUrls: ['./test02.component.scss']
})
export class Test02Component implements OnInit {
constructor(
) { }
ngOnInit() {
}
onClick() : void {
// 从浏览器缓存中获取数据【PS: 获取到的是string类型的数据】
let data = localStorage.getItem("user");
console.log(data);
// 将JSON字符串转化成对象
let json_data = JSON.parse(data);
console.log(json_data.name);
window.localStorage.removeItem("user");
}
}