> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/angular/angular/llms.txt
> Use this file to discover all available pages before exploring further.

# Common Pipes

> Built-in pipes from @angular/common for data transformation in templates

# Common Pipes

Angular's `@angular/common` package provides essential pipes for transforming and formatting data in your templates. Pipes are pure functions that transform data for display without modifying the original data.

## Date and Time

### DatePipe

Formats a date value according to locale rules.

<Tabs>
  <Tab title="Syntax">
    ```typescript theme={null}
    @Pipe({
      name: 'date'
    })
    export class DatePipe implements PipeTransform {
      transform(
        value: Date | string | number | null | undefined,
        format?: string,
        timezone?: string,
        locale?: string
      ): string | null;
    }
    ```
  </Tab>

  <Tab title="Examples">
    ```html theme={null}
    <!-- Default format (mediumDate) -->
    {{ dateObj | date }}  <!-- Jun 15, 2015 -->

    <!-- Predefined formats -->
    {{ dateObj | date:'short' }}       <!-- 6/15/15, 9:03 AM -->
    {{ dateObj | date:'medium' }}      <!-- Jun 15, 2015, 9:03:01 AM -->
    {{ dateObj | date:'long' }}        <!-- June 15, 2015 at 9:03:01 AM GMT+1 -->
    {{ dateObj | date:'full' }}        <!-- Monday, June 15, 2015 at 9:03:01 AM GMT+01:00 -->

    {{ dateObj | date:'shortDate' }}   <!-- 6/15/15 -->
    {{ dateObj | date:'mediumDate' }}  <!-- Jun 15, 2015 -->
    {{ dateObj | date:'longDate' }}    <!-- June 15, 2015 -->
    {{ dateObj | date:'fullDate' }}    <!-- Monday, June 15, 2015 -->

    {{ dateObj | date:'shortTime' }}   <!-- 9:03 AM -->
    {{ dateObj | date:'mediumTime' }}  <!-- 9:03:01 AM -->
    {{ dateObj | date:'longTime' }}    <!-- 9:03:01 AM GMT+1 -->
    {{ dateObj | date:'fullTime' }}    <!-- 9:03:01 AM GMT+01:00 -->

    <!-- Custom formats -->
    {{ dateObj | date:'yyyy-MM-dd' }}                    <!-- 2015-06-15 -->
    {{ dateObj | date:'MMM dd, yyyy' }}                  <!-- Jun 15, 2015 -->
    {{ dateObj | date:'h:mm a' }}                        <!-- 9:03 AM -->
    {{ dateObj | date:"MMM dd, yyyy 'at' hh:mm a" }}    <!-- Jun 15, 2015 at 09:03 AM -->

    <!-- With timezone -->
    {{ dateObj | date:'medium':'+0000' }}  <!-- UTC -->
    {{ dateObj | date:'short':'-0700' }}   <!-- PST -->

    <!-- With locale -->
    {{ dateObj | date:'full':'':'fr' }}    <!-- French locale -->
    ```
  </Tab>

  <Tab title="Format Options">
    Common format symbols:

    | Symbol | Meaning               | Example |
    | ------ | --------------------- | ------- |
    | `yyyy` | 4-digit year          | 2015    |
    | `yy`   | 2-digit year          | 15      |
    | `MMMM` | Month name            | June    |
    | `MMM`  | Short month           | Jun     |
    | `MM`   | Month number (padded) | 06      |
    | `M`    | Month number          | 6       |
    | `dd`   | Day (padded)          | 15      |
    | `d`    | Day                   | 15      |
    | `EEEE` | Day of week           | Monday  |
    | `EEE`  | Short day             | Mon     |
    | `HH`   | Hour 0-23 (padded)    | 09      |
    | `H`    | Hour 0-23             | 9       |
    | `hh`   | Hour 1-12 (padded)    | 09      |
    | `h`    | Hour 1-12             | 9       |
    | `mm`   | Minute (padded)       | 03      |
    | `m`    | Minute                | 3       |
    | `ss`   | Second (padded)       | 05      |
    | `s`    | Second                | 5       |
    | `a`    | AM/PM                 | AM      |
    | `z`    | Timezone              | GMT+1   |
    | `Z`    | Timezone offset       | +0100   |
  </Tab>

  <Tab title="Configuration">
    ```typescript theme={null}
    import { DATE_PIPE_DEFAULT_OPTIONS, DatePipeConfig } from '@angular/common';

    // Configure default options
    @NgModule({
      providers: [
        {
          provide: DATE_PIPE_DEFAULT_OPTIONS,
          useValue: {
            dateFormat: 'shortDate',
            timezone: '-0700'
          } as DatePipeConfig
        }
      ]
    })
    export class AppModule {}
    ```
  </Tab>
</Tabs>

**Import:**

```typescript theme={null}
import { DatePipe } from '@angular/common';
```

**Source:** `packages/common/src/pipes/date_pipe.ts:224`

<Note>
  Only the `en-US` locale data comes with Angular by default. To format dates in other languages, you must import the corresponding locale data.
</Note>

***

## Number Formatting

### CurrencyPipe

Transforms a number to a currency string, formatted according to locale rules.

<Tabs>
  <Tab title="Syntax">
    ```typescript theme={null}
    @Pipe({
      name: 'currency'
    })
    export class CurrencyPipe implements PipeTransform {
      transform(
        value: number | string | null | undefined,
        currencyCode?: string,
        display?: 'code' | 'symbol' | 'symbol-narrow' | string | boolean,
        digitsInfo?: string,
        locale?: string
      ): string | null;
    }
    ```
  </Tab>

  <Tab title="Examples">
    ```html theme={null}
    <!-- Default (USD with symbol) -->
    {{ amount | currency }}  <!-- $123.45 -->

    <!-- Different currencies -->
    {{ amount | currency:'EUR' }}  <!-- €123.45 -->
    {{ amount | currency:'GBP' }}  <!-- £123.45 -->
    {{ amount | currency:'JPY' }}  <!-- ¥123 -->

    <!-- Display options -->
    {{ amount | currency:'USD':'code' }}           <!-- USD123.45 -->
    {{ amount | currency:'USD':'symbol' }}         <!-- $123.45 -->
    {{ amount | currency:'USD':'symbol-narrow' }}  <!-- $123.45 -->
    {{ amount | currency:'USD':'' }}               <!-- 123.45 (no symbol) -->
    {{ amount | currency:'USD':'Custom' }}         <!-- Custom123.45 -->

    <!-- Digit formatting (minInteger.minFraction-maxFraction) -->
    {{ amount | currency:'USD':'symbol':'1.0-0' }}  <!-- $123 -->
    {{ amount | currency:'USD':'symbol':'3.2-2' }}  <!-- $123.45 -->
    {{ amount | currency:'USD':'symbol':'1.2-4' }}  <!-- $123.4500 -->

    <!-- With locale -->
    {{ amount | currency:'EUR':'symbol':'1.2-2':'fr' }}  <!-- 123,45 € -->
    {{ amount | currency:'USD':'symbol':'1.2-2':'de' }}  <!-- 123,45 $ -->
    ```
  </Tab>

  <Tab title="Component">
    ```typescript theme={null}
    @Component({
      selector: 'app-price',
      template: `
        <div>
          <p>Price: {{ price | currency:currencyCode }}</p>
          <p>Total: {{ total | currency:currencyCode:'symbol':'1.2-2' }}</p>
        </div>
      `
    })
    export class PriceComponent {
      price = 99.99;
      total = 259.75;
      currencyCode = 'USD';

      setCurrency(code: string) {
        this.currencyCode = code;
      }
    }
    ```
  </Tab>
</Tabs>

**Import:**

```typescript theme={null}
import { CurrencyPipe } from '@angular/common';
```

**Source:** `packages/common/src/pipes/number_pipe.ts:220`

<Tip>
  Configure the default currency code using the `DEFAULT_CURRENCY_CODE` injection token.
</Tip>

***

## Async Data

### AsyncPipe

Unwraps a value from an asynchronous primitive (Observable or Promise).

<Tabs>
  <Tab title="Syntax">
    ```typescript theme={null}
    @Pipe({
      name: 'async',
      pure: false
    })
    export class AsyncPipe implements OnDestroy, PipeTransform {
      transform<T>(obj: Observable<T> | Subscribable<T> | PromiseLike<T> | null | undefined): T | null;
    }
    ```
  </Tab>

  <Tab title="Observable Example">
    ```typescript theme={null}
    @Component({
      selector: 'app-example',
      template: `
        <div>
          <h2>Time: {{ time$ | async }}</h2>
          <p>User: {{ user$ | async | json }}</p>
        </div>
      `
    })
    export class ExampleComponent {
      time$ = interval(1000).pipe(
        map(() => new Date())
      );

      user$ = this.http.get<User>('/api/user');

      constructor(private http: HttpClient) {}
    }
    ```
  </Tab>

  <Tab title="Promise Example">
    ```typescript theme={null}
    @Component({
      selector: 'app-example',
      template: `
        <div>
          <button (click)="resolve()">Resolve</button>
          <p>{{ greeting | async }}</p>
        </div>
      `
    })
    export class ExampleComponent {
      greeting: Promise<string> | null = null;

      resolve() {
        this.greeting = Promise.resolve('Hello!');
      }
    }
    ```
  </Tab>

  <Tab title="With ngIf">
    ```html theme={null}
    <!-- Avoid multiple subscriptions -->
    <div *ngIf="user$ | async as user">
      <h2>{{ user.name }}</h2>
      <p>{{ user.email }}</p>
      <p>{{ user.role }}</p>
    </div>

    <!-- Modern syntax -->
    @if (user$ | async; as user) {
      <div>
        <h2>{{ user.name }}</h2>
        <p>{{ user.email }}</p>
      </div>
    }
    ```
  </Tab>
</Tabs>

**Import:**

```typescript theme={null}
import { AsyncPipe } from '@angular/common';
```

**Source:** `packages/common/src/pipes/async_pipe.ts:144`

<Warning>
  The `async` pipe automatically subscribes and unsubscribes, preventing memory leaks. It marks the component for change detection when new values are emitted.
</Warning>

**Key Features:**

* Automatically subscribes to Observables
* Automatically unsubscribes on component destruction
* Handles both Observables and Promises
* Marks component for change detection on value updates
* Returns `null` until the first value is emitted

***

## Data Transformation

### JsonPipe

Converts a value into its JSON-format representation.

<Tabs>
  <Tab title="Syntax">
    ```typescript theme={null}
    @Pipe({
      name: 'json',
      pure: false
    })
    export class JsonPipe implements PipeTransform {
      transform(value: any): string;
    }
    ```
  </Tab>

  <Tab title="Examples">
    ```html theme={null}
    <!-- Simple object -->
    {{ user | json }}
    <!-- Output:
    {
      "name": "John",
      "age": 30,
      "email": "john@example.com"
    }
    -->

    <!-- Array -->
    {{ items | json }}

    <!-- Complex nested structure -->
    {{ data | json }}

    <!-- Debugging in pre tag -->
    <pre>{{ debugData | json }}</pre>

    <!-- With async pipe -->
    <pre>{{ user$ | async | json }}</pre>
    ```
  </Tab>

  <Tab title="Component">
    ```typescript theme={null}
    @Component({
      selector: 'app-debug',
      template: `
        <div>
          <h3>Debug Info</h3>
          <pre>{{ data | json }}</pre>
        </div>
      `
    })
    export class DebugComponent {
      data = {
        user: {
          id: 1,
          name: 'John Doe',
          preferences: {
            theme: 'dark',
            notifications: true
          }
        },
        timestamp: new Date()
      };
    }
    ```
  </Tab>
</Tabs>

**Import:**

```typescript theme={null}
import { JsonPipe } from '@angular/common';
```

**Source:** `packages/common/src/pipes/json_pipe.ts:33`

<Tip>
  The JSON pipe is particularly useful for debugging during development. Use it with the `<pre>` tag for formatted output.
</Tip>

***

## Additional Pipes

The Common package includes many other useful pipes:

<AccordionGroup>
  <Accordion title="DecimalPipe (number)">
    Formats numbers according to locale rules.

    ```html theme={null}
    {{ 3.14159 | number }}              <!-- 3.142 -->
    {{ 3.14159 | number:'1.0-0' }}      <!-- 3 -->
    {{ 3.14159 | number:'3.1-5' }}      <!-- 003.14159 -->
    {{ 1234.56 | number:'1.2-2':'fr' }} <!-- 1 234,56 -->
    ```
  </Accordion>

  <Accordion title="PercentPipe (percent)">
    Transforms a number to a percentage string.

    ```html theme={null}
    {{ 0.26 | percent }}          <!-- 26% -->
    {{ 0.26 | percent:'2.2-2' }}  <!-- 26.00% -->
    {{ 1.3495 | percent:'2.0-0' }} <!-- 135% -->
    ```
  </Accordion>

  <Accordion title="SlicePipe (slice)">
    Creates a new Array or String containing a subset of elements.

    ```html theme={null}
    {{ [1, 2, 3, 4, 5] | slice:1:3 }}     <!-- [2, 3] -->
    {{ 'abcdefg' | slice:0:3 }}           <!-- 'abc' -->
    {{ items | slice:0:5 }}               <!-- First 5 items -->
    ```
  </Accordion>

  <Accordion title="KeyValuePipe (keyvalue)">
    Transforms Object or Map into an array of key-value pairs.

    ```html theme={null}
    <div *ngFor="let item of object | keyvalue">
      {{ item.key }}: {{ item.value }}
    </div>
    ```
  </Accordion>

  <Accordion title="Case Conversion Pipes">
    Transform text case:

    ```html theme={null}
    {{ 'hello' | uppercase }}     <!-- HELLO -->
    {{ 'WORLD' | lowercase }}     <!-- world -->
    {{ 'john doe' | titlecase }}  <!-- John Doe -->
    ```
  </Accordion>

  <Accordion title="I18n Pipes">
    Internationalization pipes:

    * `I18nPluralPipe` - Maps a value to a string that pluralizes the value
    * `I18nSelectPipe` - Maps a string value to another string
  </Accordion>
</AccordionGroup>

***

## Usage Patterns

### Chaining Pipes

Pipes can be chained together:

```html theme={null}
{{ user$ | async | json }}
{{ dateValue | date:'short' | uppercase }}
{{ price | currency:'USD' | slice:0:5 }}
```

### Parameterized Pipes

Many pipes accept parameters:

```html theme={null}
{{ value | pipeName:parameter1:parameter2:parameter3 }}
{{ date | date:'fullDate':'UTC':'en-US' }}
{{ amount | currency:'EUR':'symbol':'1.2-2':'fr' }}
```

### Pure vs Impure Pipes

<CardGroup cols={2}>
  <Card title="Pure Pipes (Default)" icon="check">
    * Called only when input value changes
    * Better performance
    * Examples: `date`, `currency`, `uppercase`
  </Card>

  <Card title="Impure Pipes" icon="sync">
    * Called on every change detection cycle
    * Use sparingly for performance
    * Examples: `async`, `json`
  </Card>
</CardGroup>

***

## Creating Custom Pipes

You can create custom pipes for specific transformation needs:

```typescript theme={null}
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'exponential',
  standalone: true
})
export class ExponentialPipe implements PipeTransform {
  transform(value: number, exponent = 1): number {
    return Math.pow(value, exponent);
  }
}
```

Usage:

```html theme={null}
{{ 2 | exponential:3 }}  <!-- 8 -->
```

***

## Importing Pipes

<CodeGroup>
  ```typescript CommonModule theme={null}
  import { CommonModule } from '@angular/common';

  @Component({
    imports: [CommonModule],
    // ...
  })
  ```

  ```typescript Individual Imports theme={null}
  import { DatePipe, CurrencyPipe, AsyncPipe, JsonPipe } from '@angular/common';

  @Component({
    imports: [DatePipe, CurrencyPipe, AsyncPipe, JsonPipe],
    // ...
  })
  ```
</CodeGroup>

***

## Performance Tips

<AccordionGroup>
  <Accordion title="Use Pure Pipes">
    Pure pipes are more performant. Only use impure pipes (`pure: false`) when necessary.
  </Accordion>

  <Accordion title="Avoid Heavy Computations">
    Pipes are called frequently. Keep transformations lightweight or cache results.
  </Accordion>

  <Accordion title="Async Pipe Best Practices">
    * Use with `*ngIf` or `@if` to avoid multiple subscriptions
    * Prefer over manual subscribe/unsubscribe
    * Automatically handles memory cleanup
  </Accordion>
</AccordionGroup>

***

## See Also

<CardGroup cols={2}>
  <Card title="Pipes Guide" icon="filter" href="https://angular.dev/guide/pipes">
    Learn about creating custom pipes
  </Card>

  <Card title="Directives" icon="code" href="/api/common/directives">
    Common directives reference
  </Card>

  <Card title="Internationalization" icon="globe" href="https://angular.dev/guide/i18n">
    i18n and localization
  </Card>

  <Card title="RxJS" icon="stream" href="https://rxjs.dev">
    Reactive programming with Observables
  </Card>
</CardGroup>
