Reputation: 757
I'm in trouble but I can't find a correct way to do it. I used the mask = "0000000000", but he didn't answer me. I have an input that allows up to 10 numbers, EX: 1234256896, that is 10 elements. If the user enters 12345, I have to add 5 more zeros to the left, as he needs to complete the 10 numbers, the result would be like this: 0000012345. If the user enters 123, he will have to add 7 more zeros to the left.
Upvotes: 3
Views: 6757
Reputation: 18965
You can implement focusout
event of input tag and format
value with
TS code
format() {
this.mynumber = this.padLeft(this.mynumber, "0", 10);
}
padLeft(text: string, padChar: string, size: number): string {
return (String(padChar).repeat(size) + text).substr(size * -1, size);
}
HTML
<input type="text" [(ngModel)]="mynumber" (focusout)="format()">
Demo https://stackblitz.com/edit/angular-format-number-leading-0
Upvotes: 4
Reputation: 298
To get leading zero use array slice() method in javascript.
function getNumberWithLeadingZero(number) {
if (number<=9999999999) {
number = ("0000000000"+number).slice(-10);
}
return number;
}
This will return number with leading zero.
console.log(getNumberWithLeadingZero(126534));
This will return string "0000126534"
. You can revert back to initial number by using method parseInt()
number = parseInt(number)
Upvotes: 2