Angular Pipe - Tuong-Nguyen/Angular-D3-Cometd GitHub Wiki
Data Transformation
JSON.stringify()
<p>{{ ponies | json }}</p>
<p>[ { "name": "Rainbow Dash" }, { "name": "Pinkie Pie" } ]</p>
- Use in code
export class PoniesComponent {
ponies: Array<any> = [{ name: 'Rainbow Dash' }, { name: 'Pinkie Pie' }];
poniesAsJson: string;
// inject the Pipe you want
constructor(jsonPipe: JsonPipe) {
// and then call the transform method on it
this.poniesAsJson = jsonPipe.transform(this.ponies);
}
}
- Start index
- End index
<p>{{ ponies | slice:0:2 | json }}</p>
<p>{{ 'Ninja Squad' | slice:3 }}</p>
<!-- will display 'ja Squad' -->
<p>{{ 'Ninja Squad' | slice:-5 }}</p>
<!-- will display 'Squad' -->
<p>{{ 'Ninja Squad' | slice:2:-2 }}</p>
<!-- will display 'nja Squ' -->
- Dynamic value
@Component({
selector: 'ns-ponies',
template: `<div *ngFor="let pony of ponies | slice:0:size">{{ pony.name }}</div>`
})
export class PoniesComponent {
size = 2;
ponies = [
{ name: 'Rainbow Dash' },
{ name: 'Pinkie Pie' },
{ name: 'Fluttershy' }
];
}
Only display 2 ponies.
- Store the result with
as
@Component({
selector: 'ns-ponies',
template: `<div *ngFor="let pony of ponies | slice:0:2 as total; index as i">
{{ i+1 }}/{{ total.length }}: {{ pony.name }}
</div>`
})
export class PoniesComponent {
ponies: Array<any> = [
{ name: 'Rainbow Dash' },
{ name: 'Pinkie Pie' },
{ name: 'Fluttershy' }
];
}
{integerDigits}.{minFractionDigits}-{maxFractionDigits}
- integerDigits: how many numbers you want in the integer part.
- minFractionDigits: how many numbers you want at least in the decimal part.
- maxFractionDigits: how many numbers you want at most in the decimal part.
- ISO string for currency ('EUR', 'USD', ...)
- Symbol ('$', ...) optional: boolean
- Amount format.
Date pattern: 'dd/MM/yyyy', 'MM-yy', 'short', 'longDate', 'shortTime', ...
PromisePipe
and ObservablePipe
: Allow data obtained asynchronously to be displayed. It returns empty string until data is finally available. Once resolved, it triggers a change detection check.
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);
});
}
Note: Store result with as
import { PipeTransform, Pipe } from '@angular/core';
@Pipe({ name: 'fromNow' })
export class FromNowPipe implements PipeTransform {
transform(value, args) {
// do something here
}
}