Directives - Structural, Attribute & Component Directives
Angular Directives
In Angular, control flow statements are more recommended in the latest versions, but directives are still an important part of the Angular syllabus and are widely asked in interviews.
Directives are used to change the DOM appearance, behavior, and structure.
Anything visible on the UI is rendered through DOM elements, and directives control how those elements behave and look.
What Are Directives
Directives allow you to:
- Show or hide elements
- Apply conditions and loops
- Change styles and classes
- Modify the structure of the DOM
Examples of common directives are ngIf, ngFor, ngStyle, ngClass, and ngSwitch.
Types of Directives
Component Directives
Components themselves are directives.
The @Component decorator makes a class a component directive.
It contains:
- selector
- template
- styles
- imports
Because of this, components are also called component directives.
Structural Directives
Structural directives change the structure of the DOM.
They are used for:
- conditions
- loops
- switching templates
Common examples are:
*ngIf*ngFor*ngSwitch
Attribute Directives
Attribute directives change the appearance or behavior of elements.
They are mostly used for:
- styles
- classes
Common examples are:
ngStylengClass
Example of ngIf Directive
A signal is used to check whether a user is logged in.
The element is displayed only when the condition is true.
If isLogin is false, the heading will not appear.
For directives like ngIf to work, CommonModule must be imported, otherwise errors will appear.
Example of ngFor Directive
A signal is created to store multiple users.
*ngFor is used to loop through the users.
Since users is a signal, it is accessed using users().
Example of ngStyle Directive
A normal property is used to store a color.
The color is applied using ngStyle.
This changes the text color dynamically.