0
0
Angularframework~5 mins

map operator for transformation in Angular

Choose your learning style9 modes available
Introduction

The map operator helps you change data as it flows through your program. It takes each item and transforms it into something new.

You want to change numbers in a list, like doubling each number.
You receive data from a server and want to pick only some parts.
You want to format text before showing it on the screen.
You want to convert raw data into a friendlier shape for your app.
Syntax
Angular
import { map } from 'rxjs/operators';

observable$.pipe(
  map(value => transformedValue)
)

The map operator is used inside pipe() to transform each emitted value.

The function inside map takes one input and returns the transformed output.

Examples
Doubles each number from the stream and prints: 2, 4, 6.
Angular
import { of } from 'rxjs';
import { map } from 'rxjs/operators';

of(1, 2, 3).pipe(
  map(x => x * 2)
).subscribe(console.log);
Converts each fruit name to uppercase before printing.
Angular
import { of } from 'rxjs';
import { map } from 'rxjs/operators';

of('apple', 'banana').pipe(
  map(fruit => fruit.toUpperCase())
).subscribe(console.log);
Sample Program

This Angular component uses map to double numbers from 1 to 4. It shows the doubled numbers in a list on the page.

Angular
import { Component } from '@angular/core';
import { of } from 'rxjs';
import { map } from 'rxjs/operators';

@Component({
  selector: 'app-map-example',
  template: `
    <h2>Numbers doubled:</h2>
    <ul>
      <li *ngFor="let num of doubledNumbers">{{ num }}</li>
    </ul>
  `,
  standalone: true
})
export class MapExampleComponent {
  doubledNumbers: number[] = [];

  constructor() {
    of(1, 2, 3, 4).pipe(
      map(n => n * 2)
    ).subscribe(result => this.doubledNumbers.push(result));
  }
}
OutputSuccess
Important Notes

Remember to import map from rxjs/operators.

The map operator does not change the original data, it creates new transformed values.

Use subscribe to get the transformed values and use them in your app.

Summary

map changes each item in a data stream to a new form.

It is used inside pipe() with a function that returns the new value.

Great for formatting, calculating, or picking parts of data before using it.