Angular / Angular Basics

Using Directives and Pipes

In this tutorial, you'll learn how to use Angular's directives and pipes to manipulate the DOM and format data. You'll get hands-on experience with built-in directives and pipes, …

Tutorial 4 of 5 5 resources in this section

Section overview

5 resources

Introduces the core concepts of Angular, including modules, components, templates, and directives.

1. Introduction

In this tutorial, we are going to explore the use of Directives and Pipes in Angular. Angular Directives are used to manipulate the DOM (Document Object Model), while Pipes are used to format data. By the end of this tutorial, you will understand how to use built-in Angular directives and pipes, and also create your own.

What you will learn:
1. Understand what Directives and Pipes are
2. Use built-in Angular Directives and Pipes
3. Create custom Directives and Pipes

Prerequisites:
Basic understanding of Angular and TypeScript is required.

2. Step-by-Step Guide

Directives:
Angular directives are classes with a @Directive decorator. There are three kinds of directives in Angular:

  1. Components: These are directives with a template.
  2. Attribute directives: Change the appearance or behavior of an element, component, or another directive.
  3. Structural directives: Change the DOM layout by adding and removing DOM elements.

Pipes:
A pipe takes in data as input and transforms it to a desired output. Angular comes with a stock of pipes such as DatePipe, UpperCasePipe, LowerCasePipe, CurrencyPipe, etc. You can also create your own custom pipes.

3. Code Examples

Example 1 - Using built-in Directives:

//app.component.html
<div *ngIf="showDiv">Hello, I am a div.</div>
<button (click)="toggleDiv()">Toggle Div</button>

//app.component.ts
export class AppComponent {
  showDiv = true;

  toggleDiv() {
    this.showDiv = !this.showDiv;
  }
}

In the above example, *ngIf is a built-in Angular structural directive that adds or removes an HTML element. The div will only be displayed if showDiv is true.

Example 2 - Using built-in Pipes:

//app.component.html
<div>{{ today | date:'MM/dd/yyyy' }}</div>

//app.component.ts
export class AppComponent {
  today = Date.now();
}

In this example, date is a built-in pipe that formats a date value according to locale rules.

Example 3 - Creating custom Directive:

//highlight.directive.ts
import { Directive, ElementRef } from '@angular/core';

@Directive({
  selector: '[appHighlight]'
})
export class HighlightDirective {
  constructor(el: ElementRef) {
    el.nativeElement.style.backgroundColor = 'yellow';
  }
}

This custom directive will change the background color of any HTML element it is applied to.

Example 4 - Creating custom Pipe:

//exclaim.pipe.ts
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'exclaim'
})
export class ExclaimPipe implements PipeTransform {
  transform(value: any): any {
    return value + '!!!';
  }
}

This custom pipe will add three exclamation marks to any value it is applied to.

4. Summary

We've learned about Angular Directives and Pipes, including how to use the built-in ones and create our own. Directives and Pipes are powerful tools that allow us to manipulate the DOM and format data in Angular.

Next Steps:

  • Try creating more complex custom directives and pipes.
  • Learn more about the different types of built-in Angular pipes and directives.

Additional resources:

5. Practice Exercises

Exercise 1: Create an Angular component and use the *ngIf directive to show or hide an element based on a button click.

Exercise 2: Create a custom pipe that converts a string to camelCase.

Solutions:

  1. Similar to Example 1.
  2. Create a pipe that splits the string by spaces, then transforms the first letter of each word to uppercase and the rest to lowercase, and finally joins them with no spaces.

Tips for further practice:

  • Try combining multiple built-in pipes.
  • Explore how to pass arguments to your custom pipes.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Markdown to HTML Converter

Convert Markdown to clean HTML.

Use tool

Timestamp Converter

Convert timestamps to human-readable dates.

Use tool

MD5/SHA Hash Generator

Generate MD5, SHA-1, SHA-256, or SHA-512 hashes.

Use tool

Favicon Generator

Create favicons from images.

Use tool

Base64 Encoder/Decoder

Encode and decode Base64 strings.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help