内置属性型指令
NgClass —— 添加和删除一组 CSS 类。
NgStyle —— 添加和删除一组 HTML 样式。
NgModel —— 将数据双向绑定添加到 HTML 表单元素。
内置结构型指令
NgIf —— 从模板中创建或销毁子视图。
NgFor —— 为列表中的每个条目重复渲染一个节点。
NgSwitch —— 一组在备用视图之间切换的指令。
要在特定条件为 true 时复写 HTML 块,请将 *ngIf 放在 *ngFor 元素的容器元素上。它们之一或两者都可以是
,这样你就不必引入额外的 HTML 层次了。
属性型指令
clickout.directive.ts
import { Directive, Input, EventEmitter, Output, ElementRef, HostListener, Renderer2, OnDestroy } from '@angular/core'
@Directive({
selector: '[appClickout]'
})
export class ClickoutDirective implements OnDestroy {
@Input('appClickout') targetDom: ElementRef
@Output() showEvent = new EventEmitter()
clickEvent
constructor(el: ElementRef, render: Renderer2) {
this.clickEvent = render.listen('document', 'click', (evt) => {
if (!this.targetDom) {
return
}
if (el.nativeElement.contains(evt.target) ||
(this.targetDom && this.targetDom.nativeElement.contains(evt.target) ||
(evt.target.nodeName === 'svg' || evt.target.nodeName === 'rect' || evt.target.nodeName === 'polygon')) ||
(evt.target.offsetParent && evt.target.offsetParent.className.indexOf('cdk-overlay-container') >= 0)) {
evt.stopPropagation()
evt.preventDefault()
return false
} else {
this.showEvent.emit(false)
}
})
}
ngOnDestroy() {
if (this.clickEvent) {
this.clickEvent();
}
}
}
引入
@NgModule ....
declarations:[ClickoutDirective ]
应用
<div class="editState" #orderStatus appClickout [appClickout]="orderStatusInit" (showEvent)="editShow('editState')">
@ViewChild('orderStatus', { static: false }) orderStatus: ElementRef;
ngAfterViewInit(): void {
this.orderStatusInit = this.orderStatus;
}
editShow(event) {
switch (event) {
case 'editState':
this.editState = false;
break;
case 'editLeavel':
this.editLeavel = false;
break;
}
}