9 } from '@angular/core';
10 import { NgControl } from '@angular/forms';
12 import _ from 'lodash';
14 import { DimlessBinaryPipe } from '../pipes/dimless-binary.pipe';
15 import { FormatterService } from '../services/formatter.service';
18 selector: '[cdDimlessBinary]'
20 export class DimlessBinaryDirective implements OnInit {
22 ngModelChange: EventEmitter<any> = new EventEmitter();
25 * Minimum size in bytes.
26 * If user enter a value lower than <minBytes>,
27 * the model will automatically be update to <minBytes>.
29 * If <roundPower> is used, this value should be a power of <roundPower>.
32 * Given minBytes=4096 (4KiB), if user type 1KiB, then model will be updated to 4KiB
38 * Maximum size in bytes.
39 * If user enter a value greater than <maxBytes>,
40 * the model will automatically be update to <maxBytes>.
42 * If <roundPower> is used, this value should be a power of <roundPower>.
45 * Given maxBytes=3145728 (3MiB), if user type 4MiB, then model will be updated to 3MiB
51 * Value will be rounded up the nearest power of <roundPower>
54 * Given roundPower=2, if user type 7KiB, then model will be updated to 8KiB
55 * Given roundPower=2, if user type 5KiB, then model will be updated to 4KiB
61 * Default unit that should be used when user do not type a unit.
62 * By default, "MiB" will be used.
65 * Given defaultUnit=null, if user type 7, then model will be updated to 7MiB
66 * Given defaultUnit=k, if user type 7, then model will be updated to 7KiB
71 private el: HTMLInputElement;
74 private elementRef: ElementRef,
75 private control: NgControl,
76 private dimlessBinaryPipe: DimlessBinaryPipe,
77 private formatter: FormatterService
79 this.el = this.elementRef.nativeElement;
83 this.setValue(this.el.value);
86 setValue(value: string) {
87 if (/^[\d.]+$/.test(value)) {
88 value += this.defaultUnit || 'm';
90 const size = this.formatter.toBytes(value);
91 const roundedSize = this.round(size);
92 this.el.value = this.dimlessBinaryPipe.transform(roundedSize);
94 this.ngModelChange.emit(this.el.value);
95 this.control.control.setValue(this.el.value);
97 this.ngModelChange.emit(null);
98 this.control.control.setValue(null);
102 round(size: number) {
103 if (size !== null && size !== 0) {
104 if (!_.isUndefined(this.minBytes) && size < this.minBytes) {
105 return this.minBytes;
107 if (!_.isUndefined(this.maxBytes) && size > this.maxBytes) {
108 return this.maxBytes;
110 if (!_.isUndefined(this.roundPower)) {
111 const power = Math.round(Math.log(size) / Math.log(this.roundPower));
112 return Math.pow(this.roundPower, power);
118 @HostListener('blur', ['$event.target.value'])
119 onBlur(value: string) {
120 this.setValue(value);