Handle Events with Angular Directives

John Lindquist
InstructorJohn Lindquist
Share this video with your friends

Social Share Links

Send Tweet
Published 7 years ago
Updated 5 years ago

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.

[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.

egghead
egghead
~ 29 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today