Write an Angular Directive

John Lindquist
InstructorJohn Lindquist
Share this video with your friends

Social Share Links

Send Tweet
Published 8 years ago
Updated 6 years ago

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

[00:00] 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.

[00:10] 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.

[00:27] 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.

[00:36] 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."

[00:49] 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.

[00:59] 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.

[01:16] 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.

Hugo
Hugo
~ 7 years ago

This does not work in Angular 4.2.4

Hugo
Hugo
~ 7 years ago

Could not edit above remark. It is working :) I should not be doing this late at night :D Forgot to import the directive in app.module.ts

Elvis Sánchez
Elvis Sánchez
~ 5 years ago

:)

Markdown supported.
Become a member to join the discussionEnroll Today