This Lesson is for Members

Subscribe today and get access to all lessons! Plus direct HD download for offline use, enhances transcripts, member comment forums, and iTunes "podcast" RSS feed. Level up your skills now!

Unlock This Lesson

Already subscribed? Sign In

Autoplay

    Angular 2 - First Directive (es5)

    John LindquistJohn Lindquist

    Directives in Angular 2 are basically Components without templates. Directives allow you to interact with other components. In this video, we'll use Directive's hostListeners and Directives hostProperties to set up those relationships.

    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 Directives in Angular 2 are basically components without templates or view annotations. Or you could think a component is a directive with a view annotation. Either way you want to think about it is fine with me. Let's go ahead and create our first directive here. We'll call him "clicky." Then this directive also requires annotations just like our component did, and instead of new Angular component annotation we'll do new Angular directive annotation.

    00:32 And our selector is going to be brackets with clicky inside of it, so brackets mean it's an attribute of clicky. Let's keep checking if this is working by saying, "Is this thing on?" Then we just need to add clicky to our list of directives inside of our component, as well as add the clicky attributes somewhere on our component template, so I'll hit save, and you can see that yes, this thing is on.

    01:00 Now the way you interact between a directive and a component is by treating the component as a host. So if you look at clicky, you can see that this H1 is the host of this clicky attribute, so anything that's on this H1 will be considered a host listener or a host property. To set up a host listener, we'll say host.listeners and this is just an object where we say something like click is the name of the event we want to listen to, and then onClick is how we'll handle it.

    01:32 So we can just handle onClick inside of here, so onClick. Then we'll just log out, "You clicked my host." So hit save, come over here, click on our app, and you can see that you clicked my host. Now for properties I can just say host properties which is also an object, and the property we're going to grab is just the text content which will just allow us to change that inner text of this H1. So instead of logging this out, I can say, this text content is equal to "Is this thing on?"

    02:10 When I click on it, I can say this.textcontent You clicked my host." I'll hit save, come over here you can see it already says is this thing on? Come and click on it, and it changes to "You clicked my host."

    Discuss

    Discuss