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

How to add an event to the body tag in Angular?

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

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

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

(click)="myMethod()" 

还有 xyz.component.ts

中的类似内容
public myMethod(): void {
    // do something here
}

由于我在 Angular 方面的知识有限,除了将事件直接添加到 body 标签之外,我想不出更好的方法,如下所示:

<body onscroll="myMethod()">

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

<head>
    <script>
        function myMethod(){
            // do something here
        }
    </script>
</head>

我尝试在 app.component.ts 中的 class 内向正文 (window/document) 添加一个事件侦听器,如下所示:

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

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

您可以使用 Hostlistener.

从您的组件或指令访问 document/window 滚动事件

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

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
    }
}

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