Angular: DOCUMENT

不用原生的 document,是因为不利于后端渲染,所以避免使用原生浏览器的对象

typescript 复制代码
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;
    ...
  }
}
相关推荐
谷粒.14 小时前
Cypress vs Playwright vs Selenium:现代Web自动化测试框架深度评测
java·前端·网络·人工智能·python·selenium·测试工具
Hy行者勇哥15 小时前
HTML5 + 原生 CSS + 原生 JS 网页实现攻略
javascript·css·html5
小飞侠在吗20 小时前
vue props
前端·javascript·vue.js
DsirNg21 小时前
页面栈溢出问题修复总结
前端·微信小程序
小徐_233321 小时前
uni-app 也能远程调试?使用 PageSpy 打开调试的新大门!
前端·微信小程序·uni-app
大怪v21 小时前
【Virtual World 03】上帝之手
前端·javascript
招来红月1 天前
记录JS 实用API
javascript
别叫我->学废了->lol在线等1 天前
演示 hasattr 和 ** 解包操作符
开发语言·前端·python
霍夫曼1 天前
UTC时间与本地时间转换问题
java·linux·服务器·前端·javascript
DARLING Zero two♡1 天前
浏览器里跑 AI 语音转写?Whisper Web + cpolar让本地服务跑遍全网
前端·人工智能·whisper