Angular: DOCUMENT

不用原生的 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;  // 是否监听 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;
    ...
  }
}

你可能感兴趣的:(Angular,angular.js,javascript,前端)