Listening for events on specific HTML elements

2019-09-19 08:21发布

问题:

I am trying to figure out how to listen for specific event on a specific element in angular2.

HTML

<div id="hello-world">
    Just a random message
</div>

in javascript i have this implemented as:

document.getElementById("hello-world").addEventListener("mousewheel", (e) => {
console.info(e);
});

Not sure what the proper way to implement this in Angular2, hoping someone would have a answer.

回答1:

There are several ways to achieve this:

Directives

You can create a directive which will be applied to your webcomponent/component and then, you will be able to react to event with @HostListener. Here is an example:

@Directive({
    selector: '[highlight]'
})

class HighlightDirective {
    constructor(private _element: ElementRef) {
    }

    @HostListener('click') onClick() {
        this.highlightConfig = {
            color: 'green'
        };

        this._element.nativeElement.style.backgroundColor =
            this._element.nativeElement.style.backgroundColor ? null : this.highlightConfig.color;
    }

}

and then apply this to the component:

<div highlight>here</div>

This example will change the background-color of the div when the user click. As you can see, @HostListener('click') say "Ok guys, i'll react and apply the function bellow everytime a user click on the component I am applied on"

For mousewheel, the hostlistener is:

@HostListener('mousewheel', ['$event']) onMouseWheelChrome(event: any) {
    // my code
}

Events

You also have defaults/custom events which you can apply on your components:

<div (click)="myFunc()">Here</div>


标签: angular