We are going to create a simple pipe that will show our readers an average time to read estimation.
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.
ng new demo-read-time
yarn add moment
//or
npm install moment
ng g pipe read-time
import { Pipe, PipeTransform } from '@angular/core';
import * as moment from 'moment';
import DurationConstructor = moment.unitOfTime.DurationConstructor;
@Pipe({
name: 'readingTime'
})
export class ReadingTimePipe implements PipeTransform {
transform(content: string, wpm: number = 575, unit: DurationConstructor = 'minutes', locale = 'en'): string {
const words = text.trim().split(/\s+/).length;
const duration = Math.ceil(words / wpm);
return moment.duration(duration, unit).locale(locale).humanize();
}
}
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:
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 folks, thank you for reading this post.
Go to stackblitz