版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_20282263/article/details/88029796
指令
在 Angular 中有三种类型的指令:
- 组件 — 拥有模板的指令
- 结构型指令 — 通过添加和移除 DOM 元素改变 DOM 布局的指令
- 属性型指令 — 改变元素、组件或其它指令的外观和行为的指令
结构型指令
import { Directive, ElementRef, Input, HostListener, OnInit, Renderer2 } from '@angular/core'
@Directive({
selector: '[appSpanHighLight]'
})
export class SpanHighLightDirective implements OnInit {
// 指令的输入值
@Input('appSpanHighLight') color: string
constructor(private el: ElementRef, private render: Renderer2) {}
ngOnInit() {
// this.el.nativeElement.style.color = this.color || 'green'
this.render.setStyle(this.el.nativeElement, 'color', this.color || 'green')
}
// 监听对应的事件 点击、鼠标的移入移出
@HostListener('click') click() {}
@HostListener('mouseenter') onMouseEnter() {}
@HostListener('mouseleave') onMouseLeave() {}
}
Angular2 采用 AOT 静态编译模式,这种形式下需要我们的模板类型必须是稳定和安全的,直接使用 javascript 和 jquery 语言是不稳定,因为他们的编译不会提前发现错误,所以 angular2 才会选择 javascript 的超集 typescript 语言(这种语言编译期间就能发现错误)
为了能够支持跨平台,Angular 通过抽象层封装了不同平台的差异。比如定义了抽象类 Renderer、Renderer2 、抽象类 RootRenderer 等。此外还定义了以下引用类型:ElementRef、TemplateRef、ViewRef 、ComponentRef 和 ViewContainerRef 等。
推荐 Renderer2 操作 DOM,支持跨平台
属性型指令
例如 NgIf、NgFor 和 NgSwitch
import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';
@Directive({ selector: '[appUnless]'})
export class UnlessDirective {
private hasView = false;
constructor(private templateRef: TemplateRef<any>, 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;
}
}
}
`<p *appUnless="condition">Show this sentence unless the condition is true.</p>`
<ng-template>
是一个 Angular 元素,用来渲染 HTML。 它永远不会直接显示出来。事实上,在渲染视图之前,Angular 会把 <ng-template>
及其内容替换为一个注释。结构型指令会让 <ng-template>
正常工作。
// 这里的 * 会被展开为 <ng-template>
<div *ngIf="xxx">xxx</div>
<div *appUnless="xxx"></div>
<ng-template [ngIf]="xxx">
<div>xxx</div>
</ng-template>
<ng-template [appUnless]="xxx">
<div>xxx</div>
</ng-template>