不用原生的 document,是因为不利于后端渲染,所以避免使用原生浏览器的对象
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;
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() {
this.doc.documentElement.clientWidth;
this.doc.body.offsetWidth;
this.doc.documentElement.clientHeight;
this.doc.body.offsetHeight;
...
this.doc.documentElement.scrollTop = 0;
...
}
}