Beyond the Basics: Understanding Angular Directives
An easy to digest breakdown of component, structural, and attribute directives in Angular and how to use each of them.
Table of contents
What are Angular Directives?
The primary purpose of Angular directives is to allow you to attach behavior to elements in the DOM and to manipulate DOM attributes in sophisticated ways. Angular directives are essentially instructions that tell Angular how to adjust the rendering of a template. They are a core feature of Angular, providing a way to extend the functionality of HTML by creating reusable components or manipulating the DOM in specific ways. Directives are classified into three categories:
Types of Angular Directives
Component Directives: These directives are essentially classes that allow you to attach custom behavior to elements in your application. Every Angular application has at least one component: the root component, tying all other components together. Components are used to build the application's dynamic views.
Attribute Directives: These directives change the appearance or behavior of an element, component, or another directive. For example, the
NgStyle
directive allows you to dynamically change the style of an element.Structural Directives: These directives change the DOM layout by adding and removing DOM elements. For example,
*ngFor
and*ngIf
are structural directives that allow you to iterate over a list and conditionally include an element in the DOM, respectively.
In this series, we'll be discussing each kind of directive, appropriate use cases for each of them, and when it may be beneficial to create your own custom directives.
-
What are component directives?
Characteristics of component directives
-
How structural directives work
Common structural directives
Custom structural directives
Example of a custom structural directive
-
What are attribute directives?
Common attribute directives
Creating custom attribute directives