Save 45% for a limited time.

Get access to all courses and lessons on egghead today.

Autoplay

    Write an Angular Directive

    John LindquistJohn Lindquist

    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.

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

    Discuss

    Discuss