Working with events and directives - lordoftheflies/angular-essential-training GitHub Wiki
Directives can not only handle changing host element properties via host bindings, but they can also be set up to respond to host element events via host listeners. Over in the favorite dot directive dot ts file, Let's add some hosts listeners to toggle on and off a CSS class, is dash favorite dash hovering. Angular provides another decorator for handling wiring up to host element events. The host listener decorator. Host listener is found in the angular core scoped package, just like host binding. So we can add that to the import statement. Before we use the host listener decorator, let's add another host binding for the is dash favorite dash hovering CSS class. And let's use that to decorate a favorite directive class property named hovering, setting it to a default value of false. We will toggle this value from mouse hover events to handle adding or removing the CSS class. Okay, let's add some host listeners. The host listener decorator takes in the name of the event as a string for the first argument and an optional second argument that is an array of arguments that the targeted event will emit. We want to listen for the on mouse inter event on the host element. So we write the at host listener with a pair of parentheses and set the event name to the string mouse enter. We don't need the event admitted argument so we can leave that off here. And remember, angular works with native events without the on prefix. And that is why this string value is mouse enter instead of on mouse enter. Okay, after the decorator, we need to have a function signature. This can be whatever name you want. Let's name it on mouse enter. It doesn't need a parameter, so we leave that empty. And in the function we set this dot hovering to true. We also want to listen for on mouse leave. So we add another host listener decorator passing it mouse leave. And decorate a function that we can name on mouse leave. And in this function, we set this dot hovering to false. Then over in our browser, we can inspect the media item and then mouse-over and off of the favorite icon and see the class getting applied and removed.