Creating a New Directive

Learn how to create a new directive in this lesson.

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 created:class.directive.ts and class.directive.spec.ts. The spec file is the test file for testing the directive. We’ll be ignoring this file. It won’t impact our directive.

Note: The command will also update the app.module.ts file. We’ll be looking at modules in the next section. You can safely ignore the changes made to it.

We’re going to focus on the code generated in the class.directive.ts file.

Get hands-on with 1200+ tech skills courses.