sarpay
11/24/2019 - 5:04 PM

Ng - Built-In Pipes

Reference

Symbol Formatting

{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}. (4.0-0)

  • minIntegerDigits: The minimum number of integer digits before the decimal point. Default is 1.\
  • minFractionDigits: The minimum number of digits after the decimal point. Default is 2.\
  • maxFractionDigits: The maximum number of digits after the decimal point. Default is 2.

JS

// Currency
//-----------
import {CurrencyPipe} from '@angular/common'

constructor(private cp: CurrencyPipe) { ... }

this.value = 12345;
this.value = this.cp.transform(this.value, 'USD': true: '1.0-0'); // $12,345

// Decimal
//-----------
import {DecimalPipe} from '@angular/common'

constructor(private _decimalPipe: DecimalPipe) { ... }

this.value = 12345;
this.value = this._decimalPipe.transform(this.value, '1.0-0'); // 12,345

Currency

const num = 12345.1234;

{{num | currency}}
// output => $12,345.12

{{num | currency:'CAD':'symbol':'1.0-0'}}
// output => CA$12,345

{{num | currency:'CAD':'symbol-narrow':'1.2-2'}}
// output => $12,345.12

https://angular.io/api/common/CurrencyPipe

Decimal

const num = 12345.1234;

{{num | number:'1.0-0'}}
// output => 12,345

https://angular.io/api/common/DecimalPipe

Percentage

const num = 0.259;

{{num | percent}}
// output => 26%

{{num | percent:'0.2-2'}}
// output => 25.90%

https://angular.io/api/common/PercentPipe

Async Pipe

The async pipe subscribes to an Observable or Promise and returns the latest value it has emitted.
When a new value is emitted, the async pipe marks the component to be checked for changes.
When the component gets destroyed, the async pipe unsubscribes automatically to avoid potential memory leaks.
When the reference of the expression changes, the async pipe automatically unsubscribes from the old Observable or Promise and subscribes to the new one.

@Component({
  selector: 'async-observable-pipe',
  template: '<div>Time: {{ time | async }}</div>'
})
export class AsyncObservablePipeComponent {
  time = new Observable<string>((observer: Observer<string>) => {
    setInterval(() => observer.next(new Date().toString()), 1000);
  });
}