Reputation: 93
I have my input in a mat form field :
<mat-form-field style="padding-right: 10px;">
<input matInput type="text" [ngModel]="value | formatSize" (ngModelChange)="value=+$event";
placeholder="value" [ngModelOptions]="{standalone: true}">
</mat-form-field>
My pipe
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'formatSize'})
export class FormatSize implements PipeTransform {
transform(value: number) {
return value.toLocaleString();
}
}
My goal is to display a value which is formatted like this :
1000 -> 1 000
10000 -> 10 000
...
The problem with my code is that when i enter a value greater than 9999 it displays NaN in my input and my value is ǹull
in my component.
EDIT : reproduced code in stack : https://stackblitz.com/edit/angular-7fxuqi?file=src/app/app.component.html
Upvotes: 2
Views: 1407
Reputation: 38154
You can use RegularExpression
to add space into number:
const spaces = n => String(n)
.replace(
/(?!^)(?=(?:\d{3})+$)/g,
' '
);
const numbers = [10, 1000, 10000, 100000, 1000000, 10000000]
numbers.forEach(f => console.log(spaces(f)))
Code should look like this in your pipe:
@Pipe({name: 'formatSize'})
export class FormatSize implements PipeTransform {
transform(value: number) {
return String(value).replace(
/(?!^)(?=(?:\d{3})+$)/g,
' '
);
}
}
UPDATE:
You've got NaN
because your value has spaces. So before assigning a value, we need to remove whitespades:
{{ myValue | formatSize }}<br>
<input type="text" [ngModel]="myValue | formatSize "
(ngModelChange)="removeWhitespace($event)"
placeholder="value" [ngModelOptions]="{standalone: true}">
TypeScript:
removeWhitespace(event) {
this.myValue = event.replace(/ /g,'');
}
Upvotes: 2
Reputation: 3651
It wouldn't work like that. You have to use some sort of mask solution. It's a path of great pain and misery, the most popular solution being https://github.com/text-mask/text-mask
I used it a lot and while it has a lot of issues, it is serviceable.
Upvotes: 0