Angular – Creating and Using Directives

In the previous section, we went through the Angular components. In this post, we will discuss how to create and use directives.

There are two ways to create directives: either create it manually or via Angular-CLI.

Let us try creating it manually. In your file explorer under the src/app folder, create a new file.

directives

  • Go to src/app and then right click
  • Click the New File and you’ll be ask for a filename

Let’s name the file highlight.directive.ts.

directives

  • Basic format of naming a file is “[myDirectiveName].[fileType].ts” and in this case I named it ‘highlight’

Open the newly created file and we’ll make a very basic directive class.

directives

  • First we need to import {Directive, Input, Renderer, ElementRef} from angular/core.
  • Next we added a Directives Decorator with the selector ‘myHighlight’.
  • In the expert class, we created a constructor that changes an object’s background to blue when the selector is used.

You have just manually created a Directive!

Next, we will create another using Angular-CLI. Again, let’s open our integrated terminal and type the command ng g directive [directiveName].

directives

directives

Congratulations! You’ve successfully created directives manually and via Angular-CLI. Now we’ll learn how to use them.

Just like with Components, we have to add the directive to our app.module.ts

directives

  • Highlight Directive is imported from the created directive.
  • It is also declared inside @NgModule decorator

Now, our directive is ready to use. Let’s go to back to app.component.html follow the code shown.

Screen Shot 2017-01-15 at 3.54.04 PM

Save your work and again, type ng serve on your integrated terminal.

The output should be something like this.

Screen Shot 2017-01-15 at 3.54.47 PM

You can also modify your style like this:

And you should come up with this:

Screen Shot 2017-01-15 at 3.56.05 PM

And that’s how directives are created and used. On the next tutorial article, we will cover a type of built-in directive called *ngFor.

Subscribe Now and Upgrade Your Skills Today!
Sign up now and have the latest tech tutorials delivered straight to your mailbox.

PLUS: Get exclusive member-only discounts (up to 80% OFF!!) on our top tech courses in Udemy!
We hate spam. Your email address will not be sold or shared with anyone else.