一、指令
1.1 内置指令
1.1.1 *ngIf
1.1.2 [hidden]
1.1.3 *ngFor
1.2 自定义指令
在 Angular 中,属性型指令的创建至少需要一个带有 @Directive
装饰器的控制器类。这个装饰器指定了一个选择器名称,用于标识与指令相关联的属性名称。控制器类实现了指令的功能行为。
创建指令为: ng g d directives/hover
1.2.1 创建属性型指令
需求:实现鼠标在元素上悬停时,改变起背景颜色;鼠标移开时,背景颜色消失;鼠标点击时,字体变大;鼠标松开时,字体恢复原样的功能。
创建 background-exed.directive.ts 文件,实现如下代码:
import {
AfterViewInit,
Directive,
ElementRef,
HostBinding,
HostListener,
Input,
Renderer2,
} from '@angular/core'
@Directive({
selector: '[appBackgroundExed]',
})
export class BackgroundExedDirective implements AfterViewInit {
@Input() highLightColor: string = ''
constructor(private elementRef: ElementRef, private renderer: Renderer2) {}
// 视图初始化完成后,设置背景s颜色为黄色
ngAfterViewInit(): void {
// 写法较丑,不推荐
// this.elementRef.nativeElement.style.background = 'yellow'
// 推荐这种写法 Renderer
this.renderer.setStyle(
this.elementRef.nativeElement,
'background',
'yellow'
)
}
// 为节点动态注入class
@HostBinding('class.pressed')
isPressed: boolean = false
//绑定监听事件
@HostListener('mouseenter')
onMouseEnter(): void {
this.highLight(this.highLightColor)
}
@HostListener('mouseleave')
onMouseLeave(): void {
this.highLight('')
}
@HostListener('mousedown')
onMouseDown(): void {
this.isPressed = true
}
@HostListener('mouseup')
onMouseUp(): void {
this.isPressed = false
}
// 修改背景颜色
private highLight(color: string): void {
// this.elementRef.nativeElement.style.background = color;
this.renderer.setStyle(this.elementRef.nativeElement, 'background', color)
}
}
具体细节参考:详解Angular中自定义创建指令的方法-木庄网络博客 (muzhuangnet.com)
二、管道
作用:格式化组件模板的数据
2.1 内置管道