DEV Community

Manoj
Manoj

Posted on

How to use Cleave.js in Angular application?

Quick intro to Cleave.js:

Cleave.js is a library used to format the input as a user starts typing in an field without the user having to type the delimiter “ — ” as shown in the following gif

gif

In this example, I will be showing date format with “ / ” as delimiter and “dd/mm/yyyy” as the date pattern, i.e.

{
  date: true,
  delimiter: '/',
  datePattern: ['d', 'm', 'Y']
}

Enter fullscreen mode Exit fullscreen mode

Steps to start using Cleave.js in your angular application:

1) Install Cleave.js using a package manager from terminal, here I’m using npm:

npm i cleave.js

Enter fullscreen mode Exit fullscreen mode

2) Next, add the path to Cleave.js minimal bundle to angular.json file (as shown in the image below)

"./node_modules/cleave.js/dist/cleave.min.js"
Enter fullscreen mode Exit fullscreen mode

angular.json

3) Now, declare that there will be some object called Cleave in the runtime in your component using the following snippet.

declare let Cleave: any;
Enter fullscreen mode Exit fullscreen mode

declare

4) I will be using angular material form input, but you can use regular form tags and Cleave.js will work fine. Add a custom class to the form input field as shown (you can name it anything):

form class

5) Next, let’s implement the Cleave object in the component constructor like this,

/* 
Cleave takes in two parameters, the first is classname and second is the
object which contains data describing the input format desired.
In this example, we pass in input type, delimiter and datepattern.
*/
new Cleave('.cleave-date', {
      date: true,
      delimiter: '/',
      datePattern: ['d', 'm', 'Y']
});
Enter fullscreen mode Exit fullscreen mode

constructor implementation

Notice the yellow box, it should be the same class name that has been applied to the input field in the corresponding HTML file.

Now, let’s serve it using ng serve command :)

ng serve -o

6) Uh-oh, did you also get this error and an empty screen?

error

What it means is, we are trying to access an element in the DOM that hasn’t been rendered yet. To solve this, we have to implement the code in ngOnInit() lifecycle hook and not the constructor as shown in the image below

error fix with ngOnInit

7) and… Voila! Now you can see a form field and no error in the console and when you type in the date, you can see Cleave.js into the action :)

final view

I have only showed how to use Cleave.js with date format, learn other formats from here: https://bit.ly/3WGTNtj

Happy Coding!

Top comments (1)

Collapse
 
naucode profile image
Al - Naucode

Hey, that was a nice read, you got my follow, keep writing 😉