There are also 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. 1

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


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


  • First we need to import {Directive, Input, Renderer, ElementRef} from angular/core.
  • Next we added a Directive 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].



Congratulations! You’ve successfully created a Directive 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


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.


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

The output should be something like this.


You can also modify your style like this:


and you should come up with this.


On the next article, we will be discussing Creating and Using Services.


$100,000 is the average annual salary of talented software developers and your chances of getting this salary get better by learning Angular 2 today!

Sign up now and make the first step towards upgrading your skill set.

PLUS: Get up to 75% OFF our Angular 2 course in Udemy!
We hate spam. Your email address will not be sold or shared with anyone else.