2017-04-08 13 views
0

私はangle2アプリで自分の番号をフォーマットしたいと思います。 私はいつも8つの数字で欲しいです。 ex。私が挿入する場合:angle2 toStringメソッドの具体的な数値形式は?

12345678 -> 12345678 
123 -> 0000
123456 -> 0
123456789 ->i'll display a modal error or message(don't care of this) 

私は検索しますが、私はこのケースでは使用できないパイプしか見つけません。

thaks

答えて

1

パッド開始polyfill.ts

ポリフィルから:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart

宣言から:

https://github.com/Microsoft/TypeScript/blob/master/lib/lib.es2017.string.d.ts

interface String { 
    padStart(targetLength: number, padString?: string): string; 
} 

// https://github.com/uxitten/polyfill/blob/master/string.polyfill.js 
// https://developer.mozilla.org/enUS/docs/Web/JavaScript/Reference/Global_Objects/String/padStart 

if (!String.prototype.padStart) { 
    String.prototype.padStart = function padStart(targetLength, padString) { 
    targetLength = targetLength >> 0; //floor if number or convert non-number to 0; 
    padString = String(padString || ' '); 
    if (this.length > targetLength) { 
     return String(this); 
    } 
    else { 
     targetLength = targetLength-this.length; 
     if (targetLength > padString.length) { 
     padString += padString.repeat(targetLength/padString.length); //append to original to ensure we are longer than needed 
     } 
     return padString.slice(0, targetLength) + String(this); 
    } 
    }; 
} 

パッド-start.pipe

import 'pad-start-polyfill'; 
import {Pipe} from '@angular/core'; 

@Pipe({name: 'padStart'}) export default class { 
    transform(value: string, targetLength: number, padString = ' ') { 
    return value.padStart(targetLength, padString); 
    } 
} 

temaplate-usage.html

<span> 
    {{value | padStart : 8 : '0'}} 
</span> 
1

あなたは、あなたの場合は

function pad(num, size) { 
    var s = num + ""; 
    while (s.length < size) 
     s = "0" + s; 

    return s; 
} 

ゼロで完了するための関数を作成することができますサイズ= 8

0

それを行うためのeaser方法は、インポートモジュールあんたに

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

@Pipe({ 
    name: 'minimalLenthNumber' 
}) 
export class MinimalLenthNumberPipe implements PipeTransform { 
    transform(num : number, size: number) : string { 
     var s = num + ""; 
     while (s.length < size) 
      s = "0" + s; 
     return s; 
    } 
} 

あなた-pipe.pipe.ts

の上に2つの応答をマージし、私の場合には、このパイプ ミスインポートいけない私が持っていますすべてのモジュールの私のアプリケーション

app.module.ts

import { MinimalLenthNumberPipe } from './pipes/minimal-lenth-number.pipe'; 

@NgModule({ 
    MinimalLenthNumberPipe 
} 
を持つファイルをapp.module.ts

は、あなたには、いくつかの-page.component.ts

それを使用したいMinimalLenthNumberPipeをインポート

<some-tag> {{ 12 | minimalLenthNumber: 4 }} </some-tag> 
<!-- the final result will be '0012'--> 
関連する問題