jnkrois
jnkrois

Reputation: 682

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

I would like to find out a better way to implement this functionality.

I'm trying to add an even to the body tag. I'm using Angular 4. Since the body tag (in index.html) is not processed through a component, I can't use the angular way to accomplish this.

I would normally do something like this for the xyz.component.html:

(click)="myMethod()" 

And something like this in the xyz.component.ts

public myMethod(): void {
    // do something here
}

Due to my limited knowledge in Angular, I can't think of a better way to do this, other than adding the event directly to the body tag, like this:

<body onscroll="myMethod()">

And place the actual function between script tags in the head of the index.html file itself, like so:

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

I tried adding an event listener to the body (window/document) inside the class in app.component.ts, like so:

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

This did not work for me. After I inspected the element, I could see that the event does not get attached.

Upvotes: 3

Views: 4039

Answers (1)

Vega
Vega

Reputation: 28738

You can have access to document/window scroll event from your components or directives with Hostlistener.

For example, the bellow will track the body scroll. It's used inside a directive, but you can also put it in a component.

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

This can be used with window:scroll event.

Upvotes: 5

Related Questions