This tutorial aims to provide a comprehensive understanding of Angular directives and pipes. These concepts are fundamental to creating dynamic and responsive Angular applications.
Angular Directives are classes that add additional behavior to elements in your Angular applications. They can change the appearance, behavior or layout of DOM elements.
Angular provides three types of directives:
- Component Directives: These are directives with a template.
- Attribute Directives: These change the appearance or behavior of an element, component, or another directive.
- Structural Directives: These change the DOM layout by adding and removing DOM elements.
Angular Pipes are simple functions that you can use in template expressions to accept an input value and return a transformed value. Pipes are a good way to format values in Angular.
ng generate pipe
command to create a new pipe.Pipe
and PipeTransform
from @angular/core
.Here are some practical examples of Angular directives and pipes:
// app.component.html
<div *ngIf="true">
<p>This is a paragraph.</p>
</div>
The *ngIf
directive in this code snippet is a built-in structural directive in Angular. It is used to conditionally include or exclude a block of HTML. In this case, the <p>
element is included because the condition is true
.
// app.component.html
<button [ngClass]="{'active': isActive}">Click me</button>
The [ngClass]
directive in the above snippet is a built-in attribute directive in Angular. It allows you to dynamically add or remove CSS classes to an HTML element. In this case, the 'active' CSS class is added to the button element if the isActive
condition is true
.
// app.component.html
<p>{{ 'hello' | uppercase }}</p>
In this snippet, the uppercase
pipe is used to transform the string 'hello' to 'HELLO'.
In this tutorial, we have learned about Angular directives and pipes. We've seen how to manipulate DOM elements using structural and attribute directives and how to transform data using built-in and custom pipes.
The next step in learning would be to dive into creating custom directives and pipes. You can also explore more about Angular modules and services.
// reverse.pipe.ts
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'reverse'})
export class ReversePipe implements PipeTransform {
transform(value: string): string {
return value.split('').reverse().join('');
}
}
Then use it in your component:
<p>{{ 'hello' | reverse }}</p> <!-- Outputs 'olleh' -->
// highlight.directive.ts
import {Directive, ElementRef, Renderer2} from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
constructor(private el: ElementRef, private renderer: Renderer2) {
renderer.setStyle(el.nativeElement, 'backgroundColor', 'yellow');
}
}
Then use it in your component:
<p appHighlight>Hello, world!</p> <!-- Outputs 'Hello, world!' with a yellow background -->