Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
January 29, 2023 04:49 pm GMT

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']}

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

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

npm i cleave.js

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"

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;

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, lets implement the Cleave object in the component constructor like this,

/* Cleave takes in two parameters, the first is classname and second is theobject 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']});

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, lets 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 hasnt 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!


Original Link: https://dev.to/virtualmanu/how-to-use-cleavejs-in-angular-application-42f4

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To