In this section, we will explore custom directives in Angular. Directives are a powerful feature in Angular that allow you to extend the HTML vocabulary and create reusable components. Custom directives can be used to manipulate the DOM, apply styles, and add behavior to elements.
Key Concepts
-
What are Directives?
- Directives are classes that add additional behavior to elements in your Angular applications.
- There are three types of directives in Angular:
- Component Directives: Directives with a template.
- Structural Directives: Directives that change the DOM layout by adding and removing DOM elements (e.g.,
*ngIf
,*ngFor
). - Attribute Directives: Directives that change the appearance or behavior of an element, component, or another directive (e.g.,
ngClass
,ngStyle
).
-
Creating a Custom Directive
- Custom directives are typically attribute directives.
- They are created using the
@Directive
decorator.
-
Using Custom Directives
- Custom directives can be applied to elements in your templates.
- They can interact with the host element and respond to events.
Creating a Custom Directive
Let's create a simple custom directive that changes the background color of an element when it is hovered over.
Step-by-Step Guide
-
Generate the Directive
- Use Angular CLI to generate a new directive:
ng generate directive highlight
- Use Angular CLI to generate a new directive:
-
Implement the Directive
- Open the generated
highlight.directive.ts
file and implement the directive logic:import { Directive, ElementRef, HostListener, Input } from '@angular/core'; @Directive({ selector: '[appHighlight]' }) export class HighlightDirective { @Input() appHighlight: string; constructor(private el: ElementRef) {} @HostListener('mouseenter') onMouseEnter() { this.highlight(this.appHighlight || 'yellow'); } @HostListener('mouseleave') onMouseLeave() { this.highlight(null); } private highlight(color: string) { this.el.nativeElement.style.backgroundColor = color; } }
- Open the generated
-
Use the Directive in a Template
- Apply the directive to an element in your component template:
<p appHighlight="lightblue">Hover over this text to see the highlight effect.</p>
- Apply the directive to an element in your component template:
Explanation
- @Directive Decorator: Defines the directive and its selector (
[appHighlight]
). - ElementRef: A service that grants direct access to the DOM element.
- @Input(): Binds the directive's input property to the attribute value.
- @HostListener(): Listens to events on the host element and triggers the specified methods.
- highlight() Method: Changes the background color of the host element.
Practical Exercise
Task
Create a custom directive that changes the text color of an element when it is clicked.
Steps
- Generate a new directive named
textColor
. - Implement the directive to change the text color on click.
- Use the directive in a component template.
Solution
-
Generate the Directive
ng generate directive textColor
-
Implement the Directive
import { Directive, ElementRef, HostListener, Input } from '@angular/core'; @Directive({ selector: '[appTextColor]' }) export class TextColorDirective { @Input() appTextColor: string; constructor(private el: ElementRef) {} @HostListener('click') onClick() { this.changeTextColor(this.appTextColor || 'blue'); } private changeTextColor(color: string) { this.el.nativeElement.style.color = color; } }
-
Use the Directive in a Template
<p appTextColor="red">Click this text to change its color to red.</p>
Common Mistakes and Tips
- Forgetting to Declare the Directive: Ensure that the directive is declared in the
declarations
array of your module. - Incorrect Selector: Make sure the selector in the
@Directive
decorator matches the attribute used in the template. - Direct DOM Manipulation: Avoid direct DOM manipulation when possible. Use Angular's built-in methods and services.
Summary
In this section, we learned about custom directives in Angular. We created a custom directive to change the background color of an element on hover and another to change the text color on click. Custom directives are a powerful way to encapsulate and reuse behavior across your application. In the next section, we will explore services and dependency injection in Angular.
Angular Course
Module 1: Introduction to Angular
- What is Angular?
- Setting Up the Development Environment
- Angular Architecture
- First Angular Application
Module 2: Angular Components
- Understanding Components
- Creating Components
- Component Templates
- Component Styles
- Component Interaction
Module 3: Data Binding and Directives
- Interpolation and Property Binding
- Event Binding
- Two-Way Data Binding
- Built-in Directives
- Custom Directives
Module 4: Services and Dependency Injection
Module 5: Routing and Navigation
Module 6: Forms in Angular
Module 7: HTTP Client and Observables
- Introduction to HTTP Client
- Making HTTP Requests
- Handling HTTP Responses
- Using Observables
- Error Handling
Module 8: State Management
- Introduction to State Management
- Using Services for State Management
- NgRx Store
- NgRx Effects
- NgRx Entity
Module 9: Testing in Angular
Module 10: Advanced Angular Concepts
- Angular Universal
- Performance Optimization
- Internationalization (i18n)
- Custom Pipes
- Angular Animations