> For the complete documentation index, see [llms.txt](https://briebug.gitbook.io/angular-fundamentals/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://briebug.gitbook.io/angular-fundamentals/directives.md).

# 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

![](https://3208804520-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LHxcOLKU4vpIQfXJm9H%2F-Ll2MKVTu6yOp2S5XSUI%2F-Ll2Mv00A0ldKFd6FpnK%2Fdirectives.jpg?alt=media\&token=8a3161cf-6e71-4757-acb7-52752f6369f9)

## Creating custom directives

`ng generate directive highlight` or `ng g d highlight`

{% embed url="<https://stackblitz.com/edit/angular-fundamentals-ad2019-7?file=src%2Fapp%2Fhighlight.directive.ts&view=editor>" %}

{% hint style="info" %}
Why not highlight? - To avoid naming conflicts, Angular prepends the application name to the selector to ensure uniqueness.
{% endhint %}

{% hint style="info" %}
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.
{% endhint %}

### Directive Usage

{% code title="my.component.html" %}

```markup
<p appHighlight>This is highlighted text</p>
```

{% endcode %}

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

{% embed url="<https://stackblitz.com/edit/angular-fundamentals-ad2019-7dot5?file=src%2Fapp%2Fhighlight.directive.ts&view=editor>" %}

{% hint style="info" %}
The `@HostListener` decorator lets you subscribe to events of the DOM element that hosts an attribute directive.
{% endhint %}

## Passing Inputs to a Directive

{% embed url="<https://stackblitz.com/edit/angular-fundamentals-ad2019-7dot9?file=src%2Fapp%2Fhighlight.directive.ts&view=editor>" %}

{% code title="my.component.ts" %}

```markup
<p appHighlight="red">This is highlighted text</p>
```

{% endcode %}

## Summary

* What are directives?
* Creating custom directives
* Handling user events
* Passing inputs to directive
