在Angular 8中如何显示转换后的值?

huangapple go评论93阅读模式
英文:

How to show converted value in angular 8?

问题

在我的项目中,我在后端使用.NET Core 2.2,前端使用Angular 8。情景是我在后端有一些整数值,具有一定的范围。例如:

[Required]
[Range(1073741824, 1099511627776)] // 1GB -> 1TB
public long DiskSize { get; set; }

为了显示这些值,我使用了ng-slider5。我的TypeScript文件如下:

diskOptions: Options = {
    floor: 1073741824,
    ceil: 1099511627776
};

我的HTML文件如下:

<div class="input-group mt-1">
    <div class="input-group-prepend">
        <div class="input-group-text">
            <i class="fas fa-hdd text-primary"></i>&nbsp;Disk Size
        </div>
    </div>
    <ng5-slider [(value)]="model.diskSize" name="diskSize" [(ngModel)]="model.diskSize" [options]="diskOptions" class="form-control"></ng5-slider>
</div>

我想要在滑块上实现的是,不显示数值,而是以1GB的增量显示,直到1TB。同时,显示GB,并在1024GB时切换到TB。滑块看起来像这样:

在Angular 8中如何显示转换后的值?

英文:

In my project I am using .net core 2.2 for backend and angular 8 for front end. Scenario is I have some integer values in backend with some range. For ex:

    [Required]
    [Range(1073741824, 1099511627776)] // 1GB -&gt; 1TB
    public long DiskSize { get; set; }

For showing values I am using ng-slider5
My typescript file looks like:

diskOptions: Options = {
    floor: 1073741824,
    ceil: 1099511627776
  };

My html file looks like:

 &lt;div class=&quot;input-group mt-1&quot;&gt;
      &lt;div class=&quot;input-group-prepend&quot;&gt;
        &lt;div class=&quot;input-group-text&quot;&gt;
          &lt;i class=&quot;fas fa-hdd text-primary&quot;&gt;&lt;/i&gt;&amp;nbsp;Disk Size
        &lt;/div&gt;
      &lt;/div&gt;     
        &lt;ng5-slider [(value)]=&quot;model.diskSize&quot; name=&quot;diskSize&quot; [(ngModel)]=&quot;model.diskSize&quot; 
     [options]=&quot;diskOptions&quot; class=&quot;form-control&quot;&gt;&lt;/ng5-slider&gt;
    &lt;/div&gt;

I would like to implement in slider showing not values but instead of 1gb increment by 1gb until 1tb.
Also show gb and change tb when 1024gb.
Slider looks like:

在Angular 8中如何显示转换后的值?

答案1

得分: 2

I have found this pipe from this repository. Try implementing this in your angular application.

bytes.pipe.ts

import { Pipe, PipeTransform, NgModule } from '@angular/core';
import { isNumberFinite, isPositive, isInteger, toDecimal } from '../utils/utils';

export type ByteUnit = 'B' | 'kB' | 'KB' | 'MB' | 'GB' | 'TB';

@Pipe({
  name: 'bytes',
})
export class BytesPipe implements PipeTransform {
  static formats: { [key: string]: { max: number; prev?: ByteUnit } } = {
    B: { max: 1024 },
    kB: { max: Math.pow(1024, 2), prev: 'B' },
    KB: { max: Math.pow(1024, 2), prev: 'B' }, // Backward compatible
    MB: { max: Math.pow(1024, 3), prev: 'kB' },
    GB: { max: Math.pow(1024, 4), prev: 'MB' },
    TB: { max: Number.MAX_SAFE_INTEGER, prev: 'GB' },
  };

  transform(input: any, decimal: number = 0, from: ByteUnit = 'B', to?: ByteUnit): any {
    if (!(isNumberFinite(input) && isNumberFinite(decimal) && isInteger(decimal) && isPositive(decimal))) {
      return input;
    }

    let bytes = input;
    let unit = from;
    while (unit !== 'B') {
      bytes *= 1024;
      unit = BytesPipe.formats[unit].prev!;
    }

    if (to) {
      const format = BytesPipe.formats[to];

      const result = toDecimal(BytesPipe.calculateResult(format, bytes), decimal);

      return BytesPipe.formatResult(result, to);
    }

    for (const key in BytesPipe.formats) {
      if (BytesPipe.formats.hasOwnProperty(key)) {
        const format = BytesPipe.formats[key];
        if (bytes < format.max) {
          const result = toDecimal(BytesPipe.calculateResult(format, bytes), decimal);

          return BytesPipe.formatResult(result, key);
        }
      }
    }
  }

  static formatResult(result: number, unit: string): string {
    return `${result} ${unit}`;
  }

  static calculateResult(format: { max: number; prev?: ByteUnit }, bytes: number) {
    const prev = format.prev ? BytesPipe.formats[format.prev] : undefined;
    return prev ? bytes / prev.max : bytes;
  }
}

@NgModule({
  declarations: [BytesPipe],
  exports: [BytesPipe],
})
export class NgBytesPipeModule {}
英文:

I have found this pipe from this repository. Try implementing this in your angular application.

bytes.pipe.ts

import { Pipe, PipeTransform, NgModule } from &#39;@angular/core&#39;;
import { isNumberFinite, isPositive, isInteger, toDecimal } from &#39;../utils/utils&#39;;
export type ByteUnit = &#39;B&#39; | &#39;kB&#39; | &#39;KB&#39; | &#39;MB&#39; | &#39;GB&#39; | &#39;TB&#39;;
@Pipe({
name: &#39;bytes&#39;,
})
export class BytesPipe implements PipeTransform {
static formats: { [key: string]: { max: number; prev?: ByteUnit } } = {
B: { max: 1024 },
kB: { max: Math.pow(1024, 2), prev: &#39;B&#39; },
KB: { max: Math.pow(1024, 2), prev: &#39;B&#39; }, // Backward compatible
MB: { max: Math.pow(1024, 3), prev: &#39;kB&#39; },
GB: { max: Math.pow(1024, 4), prev: &#39;MB&#39; },
TB: { max: Number.MAX_SAFE_INTEGER, prev: &#39;GB&#39; },
};
transform(input: any, decimal: number = 0, from: ByteUnit = &#39;B&#39;, to?: ByteUnit): any {
if (!(isNumberFinite(input) &amp;&amp; isNumberFinite(decimal) &amp;&amp; isInteger(decimal) &amp;&amp; isPositive(decimal))) {
return input;
}
let bytes = input;
let unit = from;
while (unit !== &#39;B&#39;) {
bytes *= 1024;
unit = BytesPipe.formats[unit].prev!;
}
if (to) {
const format = BytesPipe.formats[to];
const result = toDecimal(BytesPipe.calculateResult(format, bytes), decimal);
return BytesPipe.formatResult(result, to);
}
for (const key in BytesPipe.formats) {
if (BytesPipe.formats.hasOwnProperty(key)) {
const format = BytesPipe.formats[key];
if (bytes &lt; format.max) {
const result = toDecimal(BytesPipe.calculateResult(format, bytes), decimal);
return BytesPipe.formatResult(result, key);
}
}
}
}
static formatResult(result: number, unit: string): string {
return `${result} ${unit}`;
}
static calculateResult(format: { max: number; prev?: ByteUnit }, bytes: number) {
const prev = format.prev ? BytesPipe.formats[format.prev] : undefined;
return prev ? bytes / prev.max : bytes;
}
}
@NgModule({
declarations: [BytesPipe],
exports: [BytesPipe],
})
export class NgBytesPipeModule {}

Utils

export type CollectionPredicate = (item?: any, index?: number, collection?: any[]) =&gt; boolean;
export function isUndefined(value: any): value is undefined {
return typeof value === &#39;undefined&#39;;
}
export function isNull(value: any): value is null {
return value === null;
}
export function isNumber(value: any): value is number {
return typeof value === &#39;number&#39;;
}
export function isNumberFinite(value: any): value is number {
return isNumber(value) &amp;&amp; isFinite(value);
}
// Not strict positive
export function isPositive(value: number): boolean {
return value &gt;= 0;
}
export function isInteger(value: number): boolean {
// No rest, is an integer
return value % 1 === 0;
}
export function isNil(value: any): value is null | undefined {
return value === null || typeof value === &#39;undefined&#39;;
}
export function isString(value: any): value is string {
return typeof value === &#39;string&#39;;
}
export function isObject(value: any): boolean {
return value !== null &amp;&amp; typeof value === &#39;object&#39;;
}
export function isArray(value: any): boolean {
return Array.isArray(value);
}
export function isFunction(value: any): boolean {
return typeof value === &#39;function&#39;;
}
export function toDecimal(value: number, decimal: number): number {
return Math.round(value * Math.pow(10, decimal)) / Math.pow(10, decimal);
}
export function upperFirst(value: string): string {
return value.slice(0, 1).toUpperCase() + value.slice(1);
}
export function createRound(method: string): Function {
// &lt;any&gt;Math to suppress error
const func: any = (&lt;any&gt;Math)[method];
return function(value: number, precision: number = 0) {
if (typeof value === &#39;string&#39;) {
throw new TypeError(&#39;Rounding method needs a number&#39;);
}
if (typeof precision !== &#39;number&#39; || isNaN(precision)) {
precision = 0;
}
if (precision) {
let pair = `${value}e`.split(&#39;e&#39;);
const val = func(`${pair[0]}e` + (+pair[1] + precision));
pair = `${val}e`.split(&#39;e&#39;);
return +(pair[0] + &#39;e&#39; + (+pair[1] - precision));
}
return func(value);
};
}
export function leftPad(str: string, len: number = 0, ch: any = &#39; &#39;) {
str = String(str);
ch = toString(ch);
let i = -1;
const length = len - str.length;
while (++i &lt; length &amp;&amp; str.length + ch.length &lt;= len) {
str = ch + str;
}
return str;
}
export function rightPad(str: string, len: number = 0, ch: any = &#39; &#39;) {
str = String(str);
ch = toString(ch);
let i = -1;
const length = len - str.length;
while (++i &lt; length &amp;&amp; str.length + ch.length &lt;= len) {
str += ch;
}
return str;
}
export function toString(value: number | string) {
return `${value}`;
}
export function pad(str: string, len: number = 0, ch: any = &#39; &#39;): string {
str = String(str);
ch = toString(ch);
let i = -1;
const length = len - str.length;
let left = true;
while (++i &lt; length) {
const l = str.length + ch.length &lt;= len ? str.length + ch.length : str.length + 1;
if (left) {
str = leftPad(str, l, ch);
} else {
str = rightPad(str, l, ch);
}
left = !left;
}
return str;
}
export function flatten(input: any[], index: number = 0): any[] {
if (index &gt;= input.length) {
return input;
}
if (isArray(input[index])) {
return flatten(input.slice(0, index).concat(input[index], input.slice(index + 1)), index);
}
return flatten(input, index + 1);
}
export function getProperty(value: { [key: string]: any }, key: string): any {
if (isNil(value) || !isObject(value)) {
return undefined;
}
const keys: string[] = key.split(&#39;.&#39;);
let result: any = value[keys.shift()!];
for (const key of keys) {
if (isNil(result) || !isObject(result)) {
return undefined;
}
result = result[key];
}
return result;
}
export function sum(input: Array&lt;number&gt;, initial = 0): number {
return input.reduce((previous: number, current: number) =&gt; previous + current, initial);
}
// http://stackoverflow.com/questions/6274339/how-can-i-shuffle-an-array-in-javascript
export function shuffle(input: any): any {
if (!isArray(input)) {
return input;
}
const copy = [...input];
for (let i = copy.length; i; --i) {
const j = Math.floor(Math.random() * i);
const x = copy[i - 1];
copy[i - 1] = copy[j];
copy[j] = x;
}
return copy;
}
export function deepIndexOf(collection: any[], value: any) {
let index = -1;
const length = collection.length;
while (++index &lt; length) {
if (deepEqual(value, collection[index])) {
return index;
}
}
return -1;
}
export function deepEqual(a: any, b: any) {
if (a === b) {
return true;
}
if (!(typeof a === &#39;object&#39; &amp;&amp; typeof b === &#39;object&#39;)) {
return a === b;
}
const keysA = Object.keys(a);
const keysB = Object.keys(b);
if (keysA.length !== keysB.length) {
return false;
}
// Test for A&#39;s keys different from B.
var hasOwn = Object.prototype.hasOwnProperty;
for (let i = 0; i &lt; keysA.length; i++) {
const key = keysA[i];
if (!hasOwn.call(b, keysA[i]) || !deepEqual(a[key], b[key])) {
return false;
}
}
return true;
}
export function isDeepObject(object: any) {
return object.__isDeepObject__;
}
export function wrapDeep(object: any) {
return new DeepWrapper(object);
}
export function unwrapDeep(object: any) {
if (isDeepObject(object)) {
return object.data;
}
return object;
}
export class DeepWrapper {
public __isDeepObject__: boolean = true;
constructor(public data: any) {}
}
export function count(input: any): any {
if (!isArray(input) &amp;&amp; !isObject(input) &amp;&amp; !isString(input)) {
return input;
}
if (isObject(input)) {
return Object.keys(input).map(value =&gt; input[value]).length;
}
return input.length;
}
export function empty(input: any): any {
if (!isArray(input)) {
return input;
}
return input.length === 0;
}
export function every(input: any, predicate: CollectionPredicate) {
if (!isArray(input) || !predicate) {
return input;
}
let result = true;
let i = -1;
while (++i &lt; input.length &amp;&amp; result) {
result = predicate(input[i], i, input);
}
return result;
}
export function takeUntil(input: any[], predicate: CollectionPredicate) {
let i = -1;
const result: any = [];
while (++i &lt; input.length &amp;&amp; !predicate(input[i], i, input)) {
result[i] = input[i];
}
return result;
}
export function takeWhile(input: any[], predicate: CollectionPredicate) {
return takeUntil(input, (item: any, index: number, collection: any[]) =&gt; !predicate(item, index, collection));
}

huangapple
  • 本文由 发表于 2020年1月7日 00:07:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/59615305.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定