如何在 Angular 中向 body 标签添加事件?

jnk*_*ois 3 javascript dom-events typescript angular2-template angular

我想找到一种更好的方法来实现此功能。

我正在尝试向 body 标签添加一个 Even 。我正在使用 Angular 4。由于 body 标记(在 index.html 中)不是通过组件处理的,因此我无法使用 Angular 方式来完成此操作。

我通常会为 xyz.component.html 做这样的事情:

(click)="myMethod()" 
Run Code Online (Sandbox Code Playgroud)

xyz.component.ts 中类似这样的东西

public myMethod(): void {
    // do something here
}
Run Code Online (Sandbox Code Playgroud)

由于我对 Angular 的了解有限,除了将事件直接添加到 body 标记之外,我想不出更好的方法来做到这一点,如下所示:

<body onscroll="myMethod()">
Run Code Online (Sandbox Code Playgroud)

并将实际函数放置在 index.html 文件本身头部的脚本标记之间,如下所示:

<head>
    <script>
        function myMethod(){
            // do something here
        }
    </script>
</head>
Run Code Online (Sandbox Code Playgroud)

我尝试将事件侦听器添加到 app.component.ts 类内的主体(窗口/文档),如下所示:

export class AppComponent implements OnInit{
    public myMethod(): void{
        window.addEventListener('myEvent', this.myEventHandler, false);
    }
}
Run Code Online (Sandbox Code Playgroud)

这对我不起作用。检查该元素后,我可以看到该事件未附加。

Veg*_*ega 5

您可以通过组件或指令访问文档/窗口滚动事件Hostlistener

例如,波纹管将跟踪正文滚动。它在指令内部使用,但您也可以将其放在组件中。

import { Directive, ElementRef, HostListener } from '@angular/core';

@Directive({ selector: '[trackScroll]' })
export class TrackScrollDirective {
    constructor(private el: ElementRef) {
}

    @HostListener('document:scroll', [])
    onScroll(): void { //will be fired on scroll event on the document
         document.querySelector('body').classList.add('newClass'); // access to the body tag
    }
}
Run Code Online (Sandbox Code Playgroud)

这可以与事件一起使用window:scroll