# 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

![](/files/-Ll2Mv00A0ldKFd6FpnK)

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


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://briebug.gitbook.io/angular-fundamentals/directives.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
