Directives

What are directives?

  • TypeScript classes to manipulate DOM elements

  • Operate on existing elements

  • Don't have a template

  • Angular provides several directives: ngStyle, ngClass, ngModel

Creating custom directives

ng generate directive highlight or ng g d highlight

Why not highlight? - To avoid naming conflicts, Angular prepends the application name to the selector to ensure uniqueness.

Adding directive to module - The Angular CLI automatically added our new directive to the nearest parent module, or app.module in this case. If you create the directive manually, you will need to add it to a parent module before using it.

Directive Usage

my.component.html
<p appHighlight>This is highlighted text</p>

Directive User Events

If we wanted to highlight the text only when the user mouses over the element, then we would need to react to user events.

The @HostListener decorator lets you subscribe to events of the DOM element that hosts an attribute directive.

Passing Inputs to a Directive

my.component.ts
<p appHighlight="red">This is highlighted text</p>

Summary

  • What are directives?

  • Creating custom directives

  • Handling user events

  • Passing inputs to directive

Last updated