import {Component} from '@angular/core';
@Component({
selector: 'hello',
template: `
<div>
<p *ngFor="let f of fileSizes">{{ f | formatFileSize }}</p>
<p>{{ largeFileSize | formatFileSize:true }}</p>
</div>`
})
export class Hello {
fileSizes = [10, 100, 1000, 10000, 100000, 10000000, 10000000000];
largeFileSize = Math.pow(10, 15)
}
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { bootstrap, platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { Hello } from './hello.component';
import { FormatFileSizePipe } from './format-file-size.pipe';
@NgModule({
imports: [
BrowserModule
],
declarations: [
Hello,
FormatFileSizePipe
],
bootstrap: [ Hello ]
})
export class AppModule {
}
platformBrowserDynamic().bootstrapModule(AppModule);
<!DOCTYPE html>
<html>
<head>
<title>Angular 2 Pipes - Custom Pipes</title>
<script src="https://unpkg.com/systemjs@0.19.38/dist/system.src.js"></script>
<script src="https://code.angularjs.org/tools/typescript.js"></script>
<script src="system.config.js"><script></script>
</head>
<body>
<hello>Loading...</hello>
<script>
System.import('app');
</script>
</body>
</html>
var angularVersion = '2.0.0';
System.config({
baseUrl: '/',
transpiler: 'typescript',
typescriptOptions: { emitDecoratorMetadata: true },
meta: {
'*': {
deps: [ 'zone.js', 'reflect-metadata' ]
}
},
paths: {
'unpkg:*': 'https://unpkg.com/*'
}
});
System.config({
packageConfigPaths: [
"unpkg:@*/*/package.json"
],
map: {
'@angular/core': 'unpkg:@angular/core@'+angularVersion,
'@angular/compiler': 'unpkg:@angular/compiler@'+angularVersion,
'@angular/common': 'unpkg:@angular/common@'+angularVersion,
'@angular/platform-browser': 'unpkg:@angular/platform-browser@'+angularVersion,
'@angular/platform-browser-dynamic': 'unpkg:@angular/platform-browser-dynamic@'+angularVersion,
'rxjs': 'unpkg:rxjs@5.0.0-beta.12',
'zone.js': 'unpkg:zone.js@0.6.23',
'reflect-metadata': 'unpkg:reflect-metadata@0.1.3',
"crypto": "@empty"
},
packages: {
'app': {
defaultExtension: 'ts',
main: './index.ts'
}
}
});
import {Pipe, PipeTransform} from '@angular/core';
const FILE_SIZE_UNITS = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
const FILE_SIZE_UNITS_LONG = ['Bytes', 'Kilobytes', 'Megabytes', 'Gigabytes', 'Pettabytes', 'Exabytes', 'Zettabytes', 'Yottabytes'];
@Pipe({
name: 'formatFileSize'
})
export class FormatFileSizePipe implements PipeTransform {
transform(sizeInBytes: number, longForm: boolean): string {
const units = longForm
? FILE_SIZE_UNITS_LONG
: FILE_SIZE_UNITS;
let power = Math.round(Math.log(sizeInBytes)/Math.log(1024));
power = Math.min(power, units.length - 1);
const size = sizeInBytes / Math.pow(1024, power); // size in new units
const formattedSize = Math.round(size * 100) / 100; // keep up to 2 decimals
const unit = units[power];
return `${formattedSize} ${unit}`;
}
}