Angular currency Mask how to input from right to left

3 min read 28-08-2024
Angular currency Mask how to input from right to left


Mastering Right-to-Left Currency Input in Angular with @ngneat/input-mask

Handling currency input in Angular applications often involves ensuring user-friendliness and accurate data formatting. This article delves into the technique of implementing right-to-left input for currency values, leveraging the powerful @ngneat/input-mask library.

The Challenge: Right-to-Left Input for Currency

Imagine a scenario where your Angular application requires users to enter monetary values. Traditionally, users enter numbers from left to right, adding digits as needed. However, for certain regions and cultures, a right-to-left input approach is more intuitive. This is particularly relevant when dealing with currencies like the Malaysian Ringgit (MYR) or the Indian Rupee (INR), where users might prefer to input the decimal part first, followed by the whole number.

Leveraging @ngneat/input-mask for Right-to-Left Currency Input

The @ngneat/input-mask library provides an elegant solution for implementing this right-to-left input functionality. Its powerful masking capabilities allow for precise control over user input, ensuring accurate currency formatting while accommodating diverse cultural preferences.

Key Components of the Solution

The code snippet provided in the question serves as a starting point:

import { createMask, InputmaskOptions } from "@ngneat/input-mask";

export const createCurrencyMask = (prefix: string = 'MYR'): InputmaskOptions<string> => {
  const regex = new RegExp(`[${prefix},\\s]`, 'g');
  return createMask({
    alias: 'numeric',
    groupSeparator: ',',
    digits: 2,
    digitsOptional: false,
    prefix: `${ prefix } `,
    placeholder: '0',
    parser: (value: string) => Number(value.replace(regex, ''))
  });
};

Let's break down the key components of this code:

  • createMask(): This function from @ngneat/input-mask is used to create a new input mask.
  • prefix: This parameter allows specifying the currency prefix (e.g., "MYR" for Malaysian Ringgit).
  • regex: A regular expression is used to remove the prefix and comma separator from the input value before parsing it as a number.
  • alias: 'numeric': This setting ensures the input is treated as a numeric value, allowing for appropriate validation and formatting.
  • groupSeparator: ',': This option defines the character used to separate thousands (e.g., "1,000,000").
  • digits: 2: This parameter sets the required number of decimal places.
  • digitsOptional: false: This prevents the user from omitting the decimal places.
  • prefix: ${ prefix } ``: This property adds the currency prefix to the input field.
  • placeholder: '0': This displays a placeholder "0" in the input field when it's empty.
  • parser: (value: string) => Number(value.replace(regex, '')): This function handles the conversion of the input value to a number, removing the prefix and group separators.

Practical Implementation in Angular

To use this custom currency mask, integrate it into your Angular component:

import { Component } from '@angular/core';
import { createCurrencyMask } from './currency-mask'; // Assuming the code above is in a separate file

@Component({
  selector: 'app-currency-input',
  template: `
    <input
      [ngModel]="amount"
      (ngModelChange)="amount = $event"
      [inputMask]="currencyMask"
      placeholder="0"
    />
    <p>Amount: {{ amount }}</p>
  `
})
export class CurrencyInputComponent {
  amount: number = 0;
  currencyMask = createCurrencyMask('MYR'); // Using MYR as the currency prefix
}

In this example, the [inputMask] directive from @ngneat/input-mask is used to apply the custom currencyMask to the input field. The ngModel directive binds the input value to the amount property in the component.

Right-to-Left Input Behavior

With this setup, the user can now enter currency values starting from the rightmost digit (the decimal part), progressively moving leftwards. The @ngneat/input-mask library handles the automatic formatting, ensuring that the input is always in the correct currency format.

Additional Considerations

  • Localization: The createCurrencyMask() function can be extended to accept additional parameters for localization, allowing you to support different currency symbols, group separators, and decimal place conventions.

  • Validation: You can further enhance the input by implementing custom validation logic to ensure that the entered values fall within specific ranges or adhere to business rules.

  • Performance Optimization: For large datasets or frequently updated input values, explore performance optimization techniques like using a ChangeDetectorRef to minimize unnecessary change detection cycles.

Conclusion

By leveraging @ngneat/input-mask and understanding the right-to-left input concept, you can build Angular applications that cater to diverse cultural preferences, providing a seamless and user-friendly experience for currency input. This approach not only simplifies the user experience but also ensures data accuracy, crucial for financial applications.