Thursday, 4 April 2019

Angular - a pipe demo

@angular/cli: 7.3.7

I was working with an interesting UI requirement, and I ended up with developing a sweet little pipe. Before I go into that, I'd describe the use case.

I have a model which has a trip plan name, and a list of locations. I am supposed to display each trip plan as a bootstrap list item. The list item should have the plan name as a list header, and the locations as a list-item-text.

Now of course, keeping in mind the small form factor, you need to ensure that when the number of locations grow in size, they should be fitted nicely into the screen.

Imagine I have an array of locations such as ['New Delhi', 'Kolkata', 'Chennai', 'Mumbai', 'Bangalore', 'Hyderabad']. I simply cannot display all of them on the screen, and going on to the next line is certainly not a great user experience. But what if the user could specify a max length, and beyond that the strings would be shortened with a "and 3 more..." or "and 5 more..."?

As an example: ['New Delhi', 'Kolkata', 'Chennai', 'Mumbai', 'Bangalore', 'Hyderabad'] gets shortened to Mumbai, Kolkata and 4 more..

To implement this, I have used a pipe, which works against a string array. It uses two methods to shorten - bestfit and sequential.

* 'bestfit': This means that that array will be sorted in ascending order of length of array items and maximum number of items will be fitted in the output string.
* 'sequential': This means that the array will be taken as is, and the first n possible items will be fitted.

Take a look at the text-shorten.pipe.ts file and play around with the 2 methods.

Source Code: GitHub


No comments:

Post a comment