Enter Your Email Address to Watch This Lesson

Your link to unlock this lesson will be sent to this email address.

Unlock this lesson and all 833 of the free egghead.io lessons, plus get Angular 2 content delivered directly to your inbox!



Existing egghead members will not see this. Sign in.

Just one more step!

Check your inbox for an email from us and click link to unlock your lesson.



Write an Angular 2 Directive

1:42 Angular 2 lesson by

Angular 2 Directives allow you manipulate elements by adding custom behaviors through attributes. This lesson covers how to create a Directive and attach its behavior to an element.

Get the Code Now
click to level up

egghead.io comment guidelines

Avatar
egghead.io

Angular 2 Directives allow you manipulate elements by adding custom behaviors through attributes. This lesson covers how to create a Directive and attach its behavior to an element.

To create our first directive, I'll go ahead and use the directive decorator, making sure to import it, and then, set up the selector for our directive.

The selector I'm going to choose is Each One so that this matches up with this. Then, this decorator is going to decorate this class. Well, let's call it "First Directive." Then make sure to add that first directive to your list of declarations.

I just want to hop back over here. If I save, it's not really going to do anything. That's because we haven't added any sort of behavior or anything to this directive.

The most divisible thing to look at is if I do, like, a host-binding picture and import that. The host-binding to inner text is, "I'm a directive."

Now, I want to hit Save. You'll see that it's completely changed the inner text of its host. h1 is the host of this directive, because that's what we've looked up.

This is looking up any property on this element and changing it based on what we said it to. That's much more common to have a directive as an attribute, you use the attribute CSS syntax to select it. Let's call this, "Look up first," as an attribute on any element.

If I say, "First," it'll create an h2. I'll leave off, "No first here." Then, what you do in h3 with the first on it. I'll say, "This will be gone." I'll hit Save. You'll see that this First wrote, "I'm a directive." Skipped this one, and added it to this one. This First is finding first and first. It doesn't find it here.

HEY, QUICK QUESTION!
Joel's Head
Why are we asking?