Join egghead, unlock knowledge.

Want more egghead? It's 45% off for a limited time only!

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock All Content for 45% Off

Already subscribed? Sign In

Save 45% for a limited time.

Get access to all courses and lessons on egghead today.

Autoplay

    Handle Events with Angular Directives

    John LindquistJohn Lindquist

    A @Directive can also listen to events on their host element using @HostListener. This allows you to add behaviors that react to user input and update or modify properties on the element without having to create a custom component.

    angularAngular
    ^6.0.0
    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    00:00 You can listen to events on the element by adding HostListeners, then typing in the name of the event as a string, so click. This is just decorating a function. Let's all say onClick, so whenever we click, let's just console.log click.

    00:16 From here, anytime I click on one of these elements, click, click, click. You'll see that click was logged out each time. Again, that's because this first selector is on each of these elements, first, first, first and its host listener is saying, "Hey. Listen for clicks on these elements."

    00:33 Now if you'd like to get access to the actual event, after the event name, you say comma and then an array of strings. $event is what we want then the event comes in here. Let's going to move this down to the next line for formatting sake.

    00:48 From here I can log out the event, it save here. Now when I want to click on each of this, I'll get the MouseEvent. Click, click, click in all the MouseEvents. Often you'll combine these HostListeners with HostBindings.

    01:01 For example, if in here I set this.first to clicked and I hit save, because inner text is bound to this first, when I click on this, this.first changes to clicked. Now the inner text is clicked. I'll click on this one, that turns into clicked and that turns into clicked.

    01:21 That's because first is here. The starting value is whatever we pass in to the attribute or the attribute directive and it's bound to that now so that whenever we change that, when that updates, whatever we're bound to will change as well.

    Discuss

    Discuss