Skip to content

Angular numeric input

Numora is an Angular numeric input library. It handles thousand separators, decimal limits, paste sanitization, scientific-notation expansion and cursor preservation in a standalone directive. Numora's value is a string end to end, so the directive works with ControlValueAccessor and FormControl<string> directly, and currency amounts never pass through IEEE 754 floating-point numbers. You need no numora-angular wrapper. The package is 8.3 kB gzipped with zero runtime dependencies.

Installation

pnpm add numora

Standalone directive with ControlValueAccessor

NumoraInput attaches directly to an existing <input> element. Implementing Angular's ControlValueAccessor on the directive lets the same <input numora> work with [(ngModel)] and Reactive Forms:

src/app/numora.directive.ts:

import { isPlatformBrowser } from '@angular/common';
import {
  ChangeDetectorRef,
  Directive,
  ElementRef,
  forwardRef,
  HostListener,
  inject,
  Input,
  OnDestroy,
  OnInit,
  PLATFORM_ID,
} from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
import { NumoraInput, type NumoraInputOptions } from 'numora';

// A bare numora attribute reaches the input as an empty string: read it as "default options".
function toOptions(value: NumoraInputOptions | ''): NumoraInputOptions {
  return value || {};
}

@Directive({
  selector: 'input[numora]',
  standalone: true,
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => NumoraDirective),
      multi: true,
    },
  ],
})
export class NumoraDirective implements ControlValueAccessor, OnInit, OnDestroy {
  private readonly el = inject<ElementRef<HTMLInputElement>>(ElementRef);
  private readonly platformId = inject(PLATFORM_ID);
  private readonly cdr = inject(ChangeDetectorRef);
  private instance!: NumoraInput;
  private pendingValue: string | null = null;
  private onChangeCb: (value: string) => void = () => {};
  private onTouchedCb: () => void = () => {};

  // Read once in ngOnInit. Later changes to the binding are not applied.
  @Input({ alias: 'numora', transform: toOptions }) options: NumoraInputOptions = {};

  ngOnInit(): void {
    // NumoraInput touches the DOM, so skip it during server rendering.
    if (!isPlatformBrowser(this.platformId)) return;

    this.instance = new NumoraInput(this.el.nativeElement, {
      ...this.options,
      // The form control stores the raw string, so forward the raw `value`.
      onValueChange: (values) => {
        this.onChangeCb(values.value);
        // Angular does not mark the view dirty for Numora's own listeners. Without this, an
        // OnPush or zoneless view that reads the control would not re-render until blur.
        this.cdr.markForCheck();
        this.options.onValueChange?.(values);
      },
    });
    if (this.pendingValue !== null) {
      this.instance.setValue(this.pendingValue);
      this.pendingValue = null;
    }
  }

  ngOnDestroy(): void {
    // Removes Numora's listeners from the adopted <input>.
    this.instance?.destroy();
  }

  @HostListener('blur')
  onBlur(): void {
    this.onTouchedCb();
  }

  writeValue(value: string | null): void {
    const next = value ?? '';
    if (this.instance) {
      this.instance.setValue(next);
    } else {
      this.pendingValue = next;
    }
  }

  registerOnChange(fn: (value: string) => void): void {
    this.onChangeCb = fn;
  }

  registerOnTouched(fn: () => void): void {
    this.onTouchedCb = fn;
  }

  setDisabledState(isDisabled: boolean): void {
    // Set on the element itself: Angular can call this before ngOnInit creates the instance.
    this.el.nativeElement.disabled = isDisabled;
  }
}

Use it directly on any <input>:

import { Component, signal } from '@angular/core';
import { NumoraDirective } from './numora.directive';

@Component({
  selector: 'app-amount',
  standalone: true,
  imports: [NumoraDirective],
  template: `
    <label>
      Amount
      <input
        [numora]="{
          decimalMaxLength: 2,
          onValueChange: handleChange,
        }"
      />
    </label>
    <p>Raw value: {{ value() }}</p>
  `,
})
export class AmountComponent {
  protected readonly value = signal('');
  protected readonly handleChange = ({ value }: { value: string }) => this.value.set(value);
}

Or use it with Reactive Forms, where the raw value goes through FormControl:

import { Component } from '@angular/core';
import { ReactiveFormsModule, FormControl } from '@angular/forms';
import { NumoraDirective } from './numora.directive';

@Component({
  selector: 'app-amount-form',
  standalone: true,
  imports: [NumoraDirective, ReactiveFormsModule],
  template: `
    <label>
      Amount
      <input
        [formControl]="amount"
        [numora]="{ decimalMaxLength: 2 }"
      />
    </label>
    <p>Raw value: {{ amount.value }}</p>
  `,
})
export class AmountFormComponent {
  protected readonly amount = new FormControl('0', { nonNullable: true });
}

A value the form sets goes through setValue(), which sanitizes it without calling onValueChange. With decimalMaxLength: 2, a control set to '1234.567' shows 1,234.56 but still holds '1234.567' until the user edits the field. Give the control values that already fit the options.

Template-driven forms work the same way with [(ngModel)]. The bare numora attribute uses the default options: the input's transform reads the empty string Angular passes for it as {}, so it also compiles under strictTemplates:

import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { NumoraDirective } from './numora.directive';

@Component({
  selector: 'app-amount-model',
  standalone: true,
  imports: [NumoraDirective, FormsModule],
  template: `
    <label>
      Amount
      <input numora [(ngModel)]="amount" />
    </label>
    <p>Raw value: {{ amount }}</p>
  `,
})
export class AmountModelComponent {
  protected amount = '0';
}

Numora adopts the <input> and sets the attributes it needs. The ControlValueAccessor methods connect it to the form. writeValue calls setValue, registerOnChange passes the raw value to the form control (see value types), and setDisabledState sets the element's disabled property. By default, Numora formats on every keystroke (see formatting).

Animated example: Numora + Torph in Angular

Stack a Torph TextMorph over a transparent-text NumoraInput. The Torph integration explains the overlay and has the shared CSS and install steps. Below is the standalone component.

import { isPlatformBrowser } from '@angular/common';
import {
  Component,
  ElementRef,
  inject,
  OnDestroy,
  OnInit,
  PLATFORM_ID,
  ViewChild,
  ViewEncapsulation,
} from '@angular/core';
import { NumoraInput } from 'numora';
import { TextMorph } from 'torph';

@Component({
  selector: 'app-numora-overlay',
  standalone: true,
  encapsulation: ViewEncapsulation.None, // Numora's <input> is created at runtime
  template: `
    <label class="numora-overlay">
      <span #display class="numora-overlay-display" aria-hidden="true">0</span>
      <div #host class="numora-overlay-host"></div>
    </label>
  `,
})
export class NumoraOverlayComponent implements OnInit, OnDestroy {
  @ViewChild('display', { static: true }) display!: ElementRef<HTMLSpanElement>;
  @ViewChild('host', { static: true }) host!: ElementRef<HTMLDivElement>;

  private morph?: TextMorph;
  private numora?: NumoraInput;
  private readonly platformId = inject(PLATFORM_ID);

  ngOnInit(): void {
    // NumoraInput and TextMorph touch the DOM, so skip them during server rendering.
    if (!isPlatformBrowser(this.platformId)) return;

    // Optional: empty the SSR placeholder up front. Torph also removes it itself.
    this.display.nativeElement.textContent = '';

    const morph = new TextMorph({
      element: this.display.nativeElement,
      ease: { stiffness: 400, damping: 30 },
    });
    this.morph = morph;

    const numora = new NumoraInput(this.host.nativeElement, {
      decimalMaxLength: 2,
      // onFormattedValueChange reports every rewrite of the field, in both formatOn modes.
      // The caret is the second argument: Torph then matches digits around the edit.
      onFormattedValueChange: (text) =>
        morph.update(text || '0', numora.element.selectionStart ?? undefined),
    });
    this.numora = numora;
    numora.element.setAttribute('aria-label', 'Amount');

    // The callback does not fire on creation, so prime the display.
    morph.update(numora.formattedValue || '0');
  }

  ngOnDestroy(): void {
    this.morph?.destroy();
    this.numora?.destroy();
    this.numora?.element.remove();
  }
}

Add the overlay CSS from the Torph page to your global styles, or to the component's styles array. In the styles array it needs ViewEncapsulation.None, because Numora creates the <input> at runtime, outside Angular's scoped styles. Global styles reach it either way.

FAQ

What is the best Angular numeric input library?

Numora is framework-agnostic TypeScript, 8.3 kB gzipped, with no runtime dependencies. In Angular you wrap NumoraInput in a standalone directive that implements ControlValueAccessor, so it works with Reactive Forms.

How do I add thousand separators to an Angular number input?

Nothing to configure. Grouping on every keystroke is the default. Numora formats as the user types and keeps the cursor between the same two digits when it inserts a comma. onValueChange receives { value, formattedValue }, where value is the raw value without separators. You can write it straight into a signal or a FormControl<string>.

Is there a numora-angular package?

No, and you do not need one. The standalone directive is the entire Angular adapter.

Does Numora integrate with Angular Reactive Forms?

Yes. The NumoraDirective implements ControlValueAccessor, so <input numora> works with [formControl] and [(ngModel)] (import FormsModule). The raw value is a string, which matches what FormControl<string> stores, so currency amounts never go through floating-point numbers.

Does it work with Angular SSR?

Yes. NumoraInput touches the DOM, so initialize it inside ngOnInit and guard with isPlatformBrowser if you target the server. Angular renders the empty <input> on the server and Numora adopts it in the browser.

Can I animate digits in Angular?

Yes. The Torph + Numora overlay pattern is vanilla DOM, so it works inside any Angular component template and Torph respects prefers-reduced-motion by default.

Why not use a native number input?

Native type="number" has no thousand separators or decimal limit, and its value is a floating-point number. Numora keeps the value as a string and preserves the cursor while formatting.