Maintain trailing zeros in numerictextbox in Angular Numerictextbox component

28 Sep 20232 minutes to read

By default, trailing zeros disappear when the NumericTextBox gets focus. However, you can use the following sample to maintain the trailing zeros while focusing the NumericTextBox.

import { Component, ViewChild } from '@angular/core';

@Component({
    selector: 'app-root',
    // specifies the template string for the NumericTextBox component

    template: `
            <ejs-numerictextbox #numeric='' id="numeric"  decimals='2' format='n2' value='10'  placeholder= 'NumericTextBox' floatLabelType= 'Always' (change)="onChange($event)" (created)="onCreate($event)" ></ejs-numerictextbox>
            `
})
export class AppComponent {
    @ViewChild('formElement') numeric?: any;
    public onChange(args: any) {
        var numericObj =  this.numeric.ej2_instances[0];
        numericObj.element.value = numericObj.formattedValue(numericObj.decimals, +numericObj.element.value);
    }
    public onCreate(args: any): void {
         document.getElementsByClassName('e-numerictextbox')[0].addEventListener('focus',() =>{
            var numericObj = this.numeric.ej2_instances[0] as any;
            numericObj.element.value = numericObj.formattedValue(numericObj.decimals, +numericObj.element.value);
        });
    }
    constructor() {
    }
}
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { NumericTextBoxModule } from '@syncfusion/ej2-angular-inputs';

/**
 * Module
 */
@NgModule({
    imports: [
        BrowserModule, NumericTextBoxModule
    ],
    declarations: [AppComponent],
    bootstrap: [AppComponent]
})
export class AppModule { }
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { enableProdMode } from '@angular/core';
import { AppModule } from './app.module';

import 'zone.js';
enableProdMode();
platformBrowserDynamic().bootstrapModule(AppModule);