• Stars
    star
    199
  • Rank 189,447 (Top 4 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created about 3 years ago
  • Updated 10 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

๐ŸŽญ @ngneat/input-mask is an angular library that creates an input mask

@ngneat/input-mask


npm (scoped) MIT commitizen PRs styled with prettier All Contributors ngneat-lib spectator semantic-release

@ngneat/input-mask is an angular library that creates an input mask. Behind the scene, it uses inputmask.

Compatibility with Angular Versions

@ngneat/input-mask Angular
4.x.x >= 11.2.7 < 13
5.x.x 13
6.x.x 14

Features

  • ๐Ÿ”ก Support for form validation
  • ๐ŸŽญ Wrapper function to easily create input-masks
  • ๐Ÿ” Helps you to convert final values to desired format
  • โ˜๏ธ Single directive to handle everything
  • ๐Ÿ›  All the configurations of inputmask provided

Installation

Angular

You can install it through Angular CLI, which is recommended:

ng add @ngneat/input-mask

or with npm

npm install @ngneat/input-mask inputmask@5
npm install -D @types/inputmask@5

When you install using npm or yarn, you will also need to import InputMaskModule in your app.module:

import { InputMaskModule } from '@ngneat/input-mask';

@NgModule({
  imports: [InputMaskModule],
})
class AppModule {}

Config

There few configuration options available with InputMaskModule:

import { InputMaskModule } from '@ngneat/input-mask';

@NgModule({
  imports: [InputMaskModule.forRoot({ inputSelector: 'input', isAsync: true })],
})
class AppModule {}
Option Type Description Default Value
inputSelector string CSS selector, which will be used with querySelector to get the native input from host element. This is useful when you want to apply input-mask to child <input> of your custom-component input
isAsync boolean If set true, MutationObserver will be used to look for changes until it finds input with inputSelector false

Usage examples

1. Date

import { Component } from '@angular/core';
import { FormControl } from '@angular/forms';
import { createMask } from '@ngneat/input-mask';

@Component({
  selector: 'app-root',
  template: `
    <input
      [inputMask]="dateInputMask"
      [formControl]="dateFC"
      placeholder="dd/mm/yyyy"
    />
  `,
})
export class AppComponent {
  dateInputMask = createMask<Date>({
    alias: 'datetime',
    inputFormat: 'dd/mm/yyyy',
    parser: (value: string) => {
      const values = value.split('/');
      const year = +values[2];
      const month = +values[1] - 1;
      const date = +values[0];
      return new Date(year, month, date);
    },
  });

  dateFC = new FormControl('');
}

2. IP Address

@Component({
  template: `
    <input
      [inputMask]="ipAddressMask"
      [formControl]="ipFC"
      placeholder="_._._._"
    />
  `,
})
export class AppComponent {
  ipAddressMask = createMask({ alias: 'ip' });
  ipFC = new FormControl('');
}

3. Currency

@Component({
  template: `
    <input
      [inputMask]="currencyInputMask"
      [formControl]="currencyFC"
      placeholder="$ 0.00"
    />
  `,
})
export class AppComponent {
  currencyInputMask = createMask({
    alias: 'numeric',
    groupSeparator: ',',
    digits: 2,
    digitsOptional: false,
    prefix: '$ ',
    placeholder: '0',
  });
  currencyFC = new FormControl('');
}

4. License Plate

@Component({
  template: `
    <input
      [inputMask]="licenseInputMask"
      [formControl]="licenseFC"
      placeholder="___-___"
    />
  `,
})
export class AppComponent {
  licenseInputMask = createMask('[9-]AAA-999');
  licenseFC = new FormControl('');
}

5. Email

@Component({
  template: `
    <input
      [inputMask]="emailInputMask"
      [formControl]="emailFC"
      placeholder="_@_._"
    />
  `,
})
export class AppComponent {
  emailInputMask = createMask({ alias: 'email' });
  emailFC = new FormControl('');
}

6. Custom Component

If you have some component and you want to apply input-mask to the inner <input> element of that component, you can do that.

For example, let's assume you have a CustomInputComponent:

@Component({
  selector: 'app-custom-input',
  template: `
    <input
      [formControl]="formControl"
      [inputMask]="inputMask"
      [placeholder]="placeholder"
    />
  `,
})
export class CustomInputComponent {
  @Input() formControl!: FormControl;
  @Input() inputMask!: InputmaskOptions<any>;
  @Input() placeholder: string | undefined;
}

And your AppComponent looks like this:

@Component({
  selector: 'app-root',
  template: `
    <app-custom-input
      [formControl]="dateFCCustom"
      [inputMask]="dateInputMaskCustom"
      placeholder="Date"
    ></app-custom-input>
  `,
})
export class AppComponent {
  dateInputMaskCustom = createMask<Date>({
    alias: 'datetime',
    inputFormat: 'dd/mm/yyyy',
    parser: (value: string) => {
      const values = value.split('/');
      const year = +values[2];
      const month = +values[1] - 1;
      const date = +values[0];
      return new Date(year, month, date);
    },
  });
  dateFCCustom = new FormControl('');
}

So to apply input-mask on CustomInputComponent, use configuration with InputMaskModule like below:

import { InputMaskModule } from '@ngneat/input-mask';

@NgModule({
  imports: [
    InputMaskModule.forRoot({
      isAsync: false, // set to true if native input is lazy loaded
      inputSelector: 'input',
    }),
  ],
})
class AppModule {}

More examples

All examples are available on stackblitz.

You can create any type of input-mask which is supported by InputMask plugin.

Validation

When [inputMask] is used with [formControl], it adds validation out-of-the box. The validation works based on isValid function.

If the validation fails, the form-control will have below error:

{ "inputMask": true }

createMask wrapper function

This library uses inputmask plugin to handle mask related tasks. So, you can use all the options available there.

The recommended way to create an inputmask is to use the createMask function provided with this library.

parser function

Apart from inputmask options, we have added one more option called parser. This basically helps you to keep the value of form-control in pre-defined format, without updating UI.

For example, you want your users to enter date in input[type=text] with dd/mm/yyyy format and you want to store a Date value in the form-control:

@Component({
  template: `
    <input
      [inputMask]="dateInputMask"
      [formControl]="dateFC"
      placeholder="dd/mm/yyyy"
    />
  `,
})
export class AppComponent {
  dateInputMask = createMask<Date>({
    alias: 'datetime',
    inputFormat: 'dd/mm/yyyy',
    parser: (value: string) => {
      const values = value.split('/');
      const year = +values[2];
      const month = +values[1] - 1;
      const date = +values[0];
      return new Date(year, month, date);
    },
  });

  dateFC = new FormControl('');
}

In above example, whenver you try to access dateFC.value, it won't be the string which user entered, but rather a Date created based on the parser function.

formatter function

Apart from the parser function, we have added one more option called formatter. This helps you if you want to change the format of a date you receive from the Database.

For example, you receive a date from your database in the format 'yyyy-MM-dd' but you want to display it 'dd/MM/yyyy'.

@Component({
  template: `
    <input
      [inputMask]="dateInputMask"
      [formControl]="dateFC"
      placeholder="dd/mm/yyyy"
    />
  `,
})
export class AppComponent {
  dateInputMask = createMask<Date>({
    alias: 'datetime',
    inputFormat: 'dd/MM/yyyy',
    formatter: (value: string) => {
      const values = value.split('-');
      const date = +values[2];
      const month = +values[1] - 1;
      const year = +values[0];
      return formatDate(new Date(year, month, date), 'dd/MM/yyyy', 'en-US');
    },
  });

  dateFC = new FormControl('1990-12-28');
}

Contributors โœจ

Thanks goes to these wonderful people (emoji key):


Dharmen Shah

๐Ÿ’ป ๐Ÿ–‹ ๐Ÿ“– ๐Ÿ’ก ๐Ÿšง ๐Ÿ“ฆ

Netanel Basal

๐Ÿ› ๐Ÿ’ผ ๐Ÿค” ๐Ÿง‘โ€๐Ÿซ ๐Ÿ“† ๐Ÿ‘€

Robin Herbots

๐Ÿค”

P. Zontrop

๐Ÿ“ฆ

Artur Androsovych

๐Ÿšง โš ๏ธ

Pawel Boguslawski

๐Ÿšง

This project follows the all-contributors specification. Contributions of any kind welcome!!

More Repositories

1

falso

All the Fake Data for All Your Real Needs ๐Ÿ™‚
TypeScript
3,098
star
2

spectator

๐ŸฆŠ ๐Ÿš€ A Powerful Tool to Simplify Your Angular Tests
TypeScript
2,029
star
3

transloco

๐Ÿš€ ๐Ÿ˜ The internationalization (i18n) library for Angular
TypeScript
1,856
star
4

until-destroy

๐ŸฆŠ RxJS operator that unsubscribe from observables on destroy
TypeScript
1,712
star
5

elf

๐Ÿง™โ€โ™€๏ธ A Reactive Store with Magical Powers
TypeScript
1,527
star
6

content-loader

โšช๏ธ SVG component to create placeholder loading, like Facebook cards loading.
TypeScript
733
star
7

hot-toast

๐Ÿž Smoking hot Notifications for Angular. Lightweight, customizable and beautiful by default.
TypeScript
687
star
8

cashew

๐Ÿฟ A flexible and straightforward library that caches HTTP requests in Angular
TypeScript
671
star
9

reactive-forms

(Angular Reactive) Forms with Benefits ๐Ÿ˜‰
TypeScript
610
star
10

tailwind

๐Ÿ”ฅ A schematic that adds Tailwind CSS to Angular applications
TypeScript
608
star
11

forms-manager

๐Ÿฆ„ The Foundation for Proper Form Management in Angular
TypeScript
517
star
12

query

๐Ÿš€ Powerful asynchronous state management, server-state utilities and data fetching for Angular Applications
TypeScript
510
star
13

error-tailor

๐Ÿฆ„ Making sure your tailor-made error solution is seamless!
TypeScript
478
star
14

helipopper

๐Ÿš A Powerful Tooltip and Popover for Angular Applications
TypeScript
392
star
15

nx-serverless

๐Ÿš€ The Ultimate Monorepo Starter for Node.js Serverless Applications
TypeScript
388
star
16

dialog

๐Ÿ‘ป A simple to use, highly customizable, and powerful modal for Angular Applications
TypeScript
371
star
17

hotkeys

๐Ÿค– A declarative library for handling hotkeys in Angular applications
TypeScript
325
star
18

edit-in-place

A flexible and unopinionated edit in place library for Angular applications
TypeScript
252
star
19

svg-icon

๐Ÿ‘ป A lightweight library that makes it easier to use SVG icons in your Angular Application
TypeScript
251
star
20

inspector

๐Ÿ•ต๏ธ An angular library that lets you inspect and change Angular component properties
TypeScript
218
star
21

dirty-check-forms

๐ŸฌDetect Unsaved Changes in Angular Forms
TypeScript
199
star
22

lib

๐Ÿค– Lets you focus on the stuff that matters
TypeScript
180
star
23

transloco-keys-manager

๐Ÿฆ„ The Key to a Better Translation Experience
TypeScript
174
star
24

dag

๐Ÿ  An Angular service for managing directed acyclic graphs
TypeScript
153
star
25

bind-query-params

Sync URL Query Params with Angular Form Controls
TypeScript
147
star
26

from-event

๐ŸฆŠ ViewChild and FromEvent โ€” a Match Made in Angular Heaven
TypeScript
137
star
27

overview

๐Ÿค– A collection of tools to make your Angular views more modular, scalable, and maintainable
TypeScript
104
star
28

aim

Angular Inline Module Schematics
TypeScript
97
star
29

cmdk

Fast, composable, unstyled command menu for Angular. Directly inspired from pacocoursey/cmdk
TypeScript
91
star
30

copy-to-clipboard

โœ‚๏ธ Modern copy to clipboard. No Flash.
TypeScript
78
star
31

variabless

JS & CSS - A Match Made in Heaven ๐Ÿ’Ž
HTML
78
star
32

loadoff

๐Ÿคฏ When it comes to loaders, take a load off your mind...
TypeScript
78
star
33

effects

๐Ÿช„ A framework-agnostic RxJS effects implementation
TypeScript
59
star
34

avvvatars

Beautifully crafted unique avatar placeholder for your next angular project.
TypeScript
42
star
35

react-rxjs

๐Ÿ”Œ "Plug and play" for Observables in React Apps!
TypeScript
37
star
36

subscribe

Subscription Handling Directive
TypeScript
34
star
37

elf-ng-router-store

Bindings to connect Angular router to Elf
TypeScript
24
star
38

ng-standalone-nx

TypeScript
24
star
39

lit-file-generator

๐ŸŽ A lit generator for a component, directive, and controller.
JavaScript
19
star
40

storage

TypeScript
18
star
41

material-schematics

TypeScript
3
star
42

svg-icon-demo

TypeScript
1
star