Angular: DOCUMENT

时间:2024-01-20 22:47:04
import { DOCUMENT } from '@angular/common'; import { Directive, Inject, Input, OnChanges, Output, Renderer2, SimpleChanges } from '@angular/core'; @Directive({ selector: '[appClickoutside]' }) export class ClickoutsideDirective implements OnChanges{ @Input() bindFlag = false; // 是否监听 document private handleClick: ()=> void; constructor( @Inject(DOCUMENT) private doc: Document, private rd: Renderer2 ) { } ngOnChanges(changes: SimpleChanges): void { if (changes['bindFlag'] && !changes['bindFlag'].firstChange) { if (this.bindFlag) { this.handleClick = this.rd.listen(this.doc, 'click', evt=> { // 点击事件的操作 }) }else { this.handleClick(); // 解绑 } } } getDocument() { // 获取 document 的属性 this.doc.documentElement.clientWidth; this.doc.body.offsetWidth; this.doc.documentElement.clientHeight; this.doc.body.offsetHeight; ... // 设置 document 的属性 this.doc.documentElement.scrollTop = 0; ... } }