A Directive modifies the DOM to change appearance, behavior or layout of DOM elements. Directives are one of the core building blocks Angular 7 uses to build applications. In fact, Angular 7 components are in large part directives with templates. From an Angular 1 perspective, Angular 7 components have assumed a lot of the roles directives used to. The majority of issues that involve templates and dependency injection rules will be done through components, and issues that involve modifying generic behavior is done through directives. There are three main types of directives in Angular 7:
- Component – directive with a template.
- Attribute directives – directives that change the behavior of a component or element but don’t affect the template
- Structural directives – directives that change the behavior of a component or element by affecting how the template is rendered.
Before the Component API shipped in Angular 1.5, directives with templates that were used as elements were defined in a similar way as an attribute directive using the same API, which could lead to messy directive declarations that can be hard to grok. Components use the directive API under the hood, but give us a cleaner interface for defining them by hiding a lot of the defaults that would otherwise be cumbersome.
Components are the most common of the three directives. Structural Directives change the structure of the view. Two examples are NgFor and NgIf. Attribute directives are used as attributes of elements. The built-in NgStyle directive in the Template Syntax guide, for example, can change several element styles at the same time.
Directive classes, like component classes, can implement life-cycle hooks to influence their configuration and behavior.
Option | Description |
selector | The CSS selector that identifies this directive in a template and triggers instantiation of the directive. |
inputs | Enumerates the set of data-bound input properties for a directive |
outputs | The set of event-bound output properties. When an output property emits an event, an event handler attached to that event in the template is invoked. |
providers | Configures the injector of this directive or component with a token that maps to a provider of a dependency. |
exportAs | The name or names that can be used in the template to assign this directive to a variable. For multiple names, use a comma-separated string. |
queries | Configures the queries that will be injected into the directive. |
jit | If true, this directive/component will be skipped by the AOT compiler and so will always be compiled using JIT. |
host | Maps class properties to host element bindings for properties, attributes, and events, using a set of key-value pairs. |