A custom pipe to better format time output

Watching the gross number of minutes summed up when lining up tasks to be done is not very intuitive, so we need a way to deconstruct this value into hours and minutes. Our pipe will have the name formattedTime and will be implemented by the formattedTimePipe class, whose unique transform method receives a number representing a total number of minutes and returns a string (proving that pipes do not need to return the same type as they receive in the payload) in a readable time format:

@Pipe({
name : 'formattedTime'
})
export class FormattedTimePipe implements PipeTransform {
transform(totalMinutes : number) {
let minutes : number = totalMinutes % 60;
let hours : numbers = Math.floor(totalMinutes / 60);
return `${hours}h:{minutes}m`;
}
}

We should not skip the opportunity to highlight that the naming convention for pipes is, the same as we saw with components, the name of the pipe class with the Pipe suffix plus a selector matching that name without the suffix. Why this mismatch between the pipe controller's class name and the selector? It is common practice to prefix the selector strings of our custom pipes and directives with a custom prefix in order to prevent collisions with other selectors defined by third party pipes and directives:

@Component({
selector : 'tasks',
styleUrls : [ 'tasks.css' ],
templateUrl : 'tasks.html'
})
export class TasksComponent {}

Finally, we just need to tweak the HTML in the tasks.html template file to ensure that our EDT expression is properly formatted:

<span class="small">
(Estimated time: {{ queued * 25 | formattedTime }})
</span>

Now, reload the page and toggle some tasks. The estimated time will be properly rendered in hours and minutes.

Lastly, we must not forget to add our Pipe construct to its module tasks.module.ts:

@NgModule({
declarations: [TasksComponent, FormattedTimePipe]
})
export class TasksModule {}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset