Search code examples
javascriptangular8mask

fill input with leading zeros


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.


Solution

  • 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