Search⌘ K

Creating a New Directive

Explore how to create a custom Angular directive that dynamically adds styles and behaviors to elements. Understand using the Angular CLI to generate directive files, applying dependency injection with ElementRef, and manipulating native DOM properties to enhance your web applications.

We'll cover the following...

We’ve become familiar with various directives in the past few lessons. It’s time to create some custom ones. The Angular CLI has a command for generating the code to create a directive. It’s the ng generate directive <name> command. The <name> portion can be replaced with the name you’d like to give the directive.

We’re going to create a directive that replicates the behavior of the ngClass directive. It will dynamically add classes to the element it’s applied to. This will give us a good idea of what’s happening behind the scenes when we use directives.

In the command line, run the following command:

ng generate directive class

In the src/app directory, two new files will be ...