Pipe - Tuong-Nguyen/Angular-D3-Cometd GitHub Wiki

Introduction

In template (View), data in Component (Model) may not suitable. Pipes can be used to transform data for displaying in template.

<p>{{ ponies | json }}</p>

Print ponies object in json format.

Custom pipe

import { PipeTransform, Pipe } from '@angular/core';
import * as moment from 'moment';

@Pipe({ name: 'fromNow' })
export class FromNowPipe implements PipeTransform {
  public transform(value, args) {
    return moment(value).fromNow();
  }
}

async pipe

Allow data got asynchronously (Promise or Observable) to display:

  • Empty string when data is not available
  • Trigger change detection check when data is available.
  • Unsubscribe Observable when component is destroyed.
import { Component } from '@angular/core';
@Component({
  selector: 'ns-greeting',
  template: `<div>{{ asyncGreeting | async }}</div>`
})
export class GreetingComponent {
  asyncGreeting = new Promise(resolve => {
  // after 1 second, the promise will resolve
    window.setTimeout(() => resolve('hello'), 1000);
  });
}
⚠️ **GitHub.com Fallback** ⚠️