Directives Introduction
Learn how Angular directives extend HTML and control the behavior, appearance, and structure of elements.
What are Directives?
Directives are special Angular features that allow you to add behavior to HTML elements or change the structure of the DOM.
Angular provides built-in directives and also allows developers to create custom directives.
Directive Flow
HTML Element
Start with an HTML element in the template.
Directive
Apply an Angular directive to the element.
Angular
Angular processes the directive.
UI Behavior
The element behavior or structure changes.
Types of Directives
Attribute Directives
Change the appearance or behavior of an existing HTML element.
ngClass
ngStyle
Structural Directives
Change the structure of the DOM by adding or removing elements.
*ngIf
*ngFor
Custom Directives
Developer-created directives used to implement application-specific behavior.
ng generate directive
Attribute Directive Example
Attribute directives modify the behavior or appearance of an existing element.
<div [ngClass]="{ active: isActive }">
Student Profile
</div>
active class is applied when
isActive is true.
Structural Directive Example
Structural directives control whether elements are created or displayed in the DOM.
<div *ngIf="isLoggedIn">
Welcome to CIIT Training Institute
</div>
isLoggedIn is true.
Custom Directive
Angular allows developers to create their own directives for reusable behavior.
ng generate directive highlight
<p appHighlight>
Angular Training
</p>
appHighlight directive can add
reusable behavior to the paragraph.
Directive Comparison
| Type | Purpose | Example |
|---|---|---|
| Attribute | Changes appearance or behavior | ngClass |
| Structural | Changes DOM structure | *ngIf |
| Custom | Provides application-specific behavior | appHighlight |
Complete Example
export class StudentComponent {
isActive = true;
isLoggedIn = true;
}
<div [ngClass]="{ active: isActive }">
<h3>Student Profile</h3>
<div *ngIf="isLoggedIn">
Welcome to Angular Training
</div>
</div>
Student Profile
Welcome to Angular Training
Why Use Directives?
Reusable
Directive behavior can be reused across components.
UI Control
Directives help control element behavior and appearance.
DOM Control
Structural directives can control DOM elements.
Custom Behavior
Developers can create directives for specific needs.
Best Practices
- Use directives when behavior needs to be reused.
- Keep custom directive logic simple and focused.
- Use meaningful directive names.
- Prefer built-in Angular directives when they solve the requirement.
- Avoid putting unnecessary business logic inside directives.
- Keep DOM-related behavior encapsulated inside directives.
Summary
- Directives extend HTML with Angular behavior.
- Attribute directives change appearance or behavior.
- Structural directives change the DOM structure.
- Custom directives provide reusable application-specific behavior.
- Directives make Angular templates more powerful and reusable.