How to create an Angular pipe that gives an estimation of reading time
In this article, we are going to create a pipe with Angular and Moment.js that will estimate reading time for blog posts.
Sometimes it’s a necessity for a company or brand to create a blog. These blog posts can be very large, so wouldn’t it be nice if we could show readers an estimation of reading time for a specific article?
In this post, we are going to create a pipe that will estimate how long an article will take to read.
- If you don’t have a project yet, create a new Angular project.
ng new demo-reading-time
2. Install moment.js
Optionally we can install moment.js so that we can present reading time humanized. (for example “2 minutes read”).
yarn add moment
// or
npm install moment
Add types for moment.js
yarn add -D @types/moment
// or
npm install @types/moment --save-dev
Note: If you don’t want to use moment.js, ignore this installation, and create your own humanized logic.
3. Create a new pipe
ng g pipe reading-time
4. Change the pipe class and method to the following
This piece of code has 4 parameters, the content
would be the text of an article/post. wpm
stands for words per minute, we can expect the following:
- Third-grade students = 150 wpm
- Eighth grade students = 250 wpm
- Average college student = 450 wpm
- Average “high-level exec” = 575 wpm
- Average college professor = 675 wpm
- Speed readers = 1,500 wpm
The unit
parameter is the duration, and locale
is used to define the language with moment.
Now we can use the pipe as follow:
<p>{{ content | readingTime }}</p>
Thats all, thank you for reading this post. Don’t hesitate to give it a clap