Angular 18 Async Pipe Example Tutorial

By Hardik Savani September 9, 2024 Category : Angular

This tutorial shows you angular 18 async pipe example. This article will give you a simple example of angular 18 async pipe. I explained simply step by step async pipe in angular 18. Here you will learn angular 18 async pipe with timer.

The Angular 18 async pipe is a built-in feature used to handle asynchronous data in Angular templates. It subscribes to Observables or Promises and automatically unwraps and displays their resolved values in the template. This simplifies asynchronous data handling in Angular applications, eliminating the need for manual subscription management in component code.

Let's see the simple example of async pipe with Observable. this example will show current time to users. it will update live time using interval function with every seconds.

So, let's follow the following steps:

Step for How to Create QR Code in Angular 18

  • Step 1: Create Angular 18 Project
  • Step 2: Update Ts File
  • Step 3: Update HTML File
  • Run Angular App

Let's follow the steps:

Step 1: Create Angular 18 Project

You can easily create your angular app using below command:

ng new my-new-app

Step 2: Update Ts File

here, we need to update ts file as like bellow with lat and long variable:

src/app/app.component.ts

import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
  
import { Observable, interval, map } from 'rxjs';
  
@Component({
  selector: 'app-root',
  standalone: true,
  imports: [CommonModule],
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  
  currentTime$: Observable;
  
  constructor() {
    /* Create an observable that emits the current time every second */
    this.currentTime$ = interval(1000).pipe(map(() => new Date()));
  }

}

Step 3: Update HTML File

here, we need to update html file as like bellow code:

src/app/app.component.html

<div class="container">
  
    <h1>Angular 18 Async Pipe Example - ItSolutionStuff.com</h1>
  
    <p>Current Time: {{ currentTime$ | async | date:'medium' }}</p>
  
</div>

Run Angular App:

All the required steps have been done, now you have to type the given below command and hit enter to run the Angular app:

ng serve

Now, Go to your web browser, type the given URL and view the app output:

http://localhost:4200

Preview:

now you can check it.

I hope it can help you...

Shares