Refactoring to Angular Pipes

Refactoring to Angular Pipes

Derived from photo by Bodey Marcoccia / flickr.com, CC BY-SA

Angular pipes are often overlooked in their simplicity. If you are familiar with filters in Angular 1.x, they are conceptually similar. At their core, they convert a set of inputs to display text in the UI. And while there are other ways to accomplish this, you may find that by using pipes you can reduce the amount of code in your components.

This is one of a series of posts detailing the process of building an application with Angular, Visual Studio, ASP.NET Core, and Azure. See the complete list of posts here.

The prior post demonstrates how to create a component using Angular Material. The component class contains a TODO comment to convert mapping logic into a pipe. This post shows how to create the pipe:

// TODO: move to own pipe or directive
private mapToDisplayDateText(date: Date): string {
    // TODO: Make today's date mockable, convert to UTC
    const todaysDate = new Date();
    const isToday = areSameDate(todaysDate, date);
    const yesterdaysDate = addDays(new Date(), -1);
    const isYesterday = areSameDate(yesterdaysDate, date);

    const dayText = isToday ? 'Today' : isYesterday ? 'Yesterday' : formatDate(date, 'dddd, MMMM, D, YYYY');
    const lastCompletedDate = `${dayText}, ${formatDate(date, 'h:mm A')}`;

    return lastCompletedDate;
}

Why Use Pipes

Admittedly, I'm a little torn on using pipes. In their pure form, the concept is straightforward: take a set of inputs and return the display output as a string. A pure JavaScript function can also accomplish the same result in a component. I sometimes view pipes as conceptual overhead that you don't necessarily need to learn when starting with Angular. The concept count is already so high for many developers. Why add pipes to the mix?

This post explores how encapsulating this mapping logic in its own UI-based wrapper, a pipe, reduces component complexity in two ways. First when mapping in the component, you are responsible for determining if a value has changed or not before mapping (or you decide not to check this at all). When using a pipe, Angular's change detection evaluates the value to determine if mapping is required.

Second, using a pipe can reduce model complexity. For instance, this example formats a date in a custom way. This date may be rendered in different ways depending on where it is shown. When mapping in the component, each component is responsible for mapping this date into the correct string format and the component is responsible for two pieces of state, the original value and the display value (or multiple display values). When this logic is encapsulated in a pipe, the view declaratively defines how the data should display and the component is only responsible for one piece of state, the date object.

Initially, I recommend sticking with pure pipes. They are more performant out of the box because they adhere to the default (and fast) Angular change detection behavior where only values and object references are compared. If you find the need to detect changes at a deeper level of an object, there are probably better ways to handle this outside the scope of a pipe – and this article.

This post isn't attempting to recreate the documentation, please read that here. Rather, this is more of a case study.

Creating the Pipe

In the initial component implementation, the pipe formats the date and replaces the day of the week text when the day is either today or yesterday. This is how the component class is written with the formatting logic in the component:

import { Component, OnInit } from '@angular/core';
import { formatDate, areSameDate, addDays } from '../utility';
import { Routine, RoutinesViewModel, RoutineViewModel } from './models';

@Component({
  selector: 'app-routines',
  templateUrl: './routines.component.html',
  styleUrls: ['./routines.component.css']
})
export class RoutinesComponent implements OnInit {
  private routines: Routine[] = [
    {
      name: 'Morning',
      lastCompletedDate: new Date()
    },
    {
      name: 'Social Media',
      lastCompletedDate: new Date(2017, 8, 23, 19, 55)
    },
    {
      name: 'Bedtime',
      lastCompletedDate: new Date(2017, 8, 5, 21, 16)
    }
  ];

  viewModel: RoutinesViewModel = {
    routines: []
  };

  ngOnInit() {
    this.render();
  }

  trackRoutine(routine: RoutineViewModel) {
    return routine.name;
  }

  // TODO: move to own pipe or directive
  private mapToDisplayDateText(date: Date): string {
    // TODO: Make today's date mockable, convert to UTC
    const todaysDate = new Date();
    const isToday = areSameDate(todaysDate, date);
    const yesterdaysDate = addDays(new Date(), -1);
    const isYesterday = areSameDate(yesterdaysDate, date);

    const dayText = isToday ? 'Today' : isYesterday ? 'Yesterday' : formatDate(date, 'dddd, MMMM, D, YYYY');
    const lastCompletedDate = `${dayText}, ${formatDate(date, 'h:mm A')}`;

    return lastCompletedDate;
  }

  private render() {
    const viewModel = {
      routines: this.routines.map(routine => {
        const routineViewModel: RoutineViewModel = {
          lastCompletedDate: this.mapToDisplayDateText(routine.lastCompletedDate),
          name: routine.name
        };

        return routineViewModel;
      })
    };

    this.viewModel = viewModel;
  }
}
<md-toolbar color="primary">
  <span>Routines</span>
</md-toolbar>

<md-nav-list>
  <md-list-item *ngFor="let routine of viewModel.routines; index as i; trackBy: trackRoutine">
    <a>
      <div md-line>
        <span class="mat-title">{{ routine.name }}</span>
      </div>
      <div md-line>
        <span class="mat-subheading-2">{{ routine.lastCompletedDate }}</span>
      </div>
    </a>
  </md-list-item>
</md-nav-list>

<a md-fab class="add-routine-button"><md-icon>add</md-icon></a>

This is the pipe and the component after refactoring:

import { Pipe, PipeTransform } from '@angular/core';
import { formatDate, areSameDate, addDays } from '../utility';

@Pipe({ name: 'todayAwareDate' })
export class TodayAwareDatePipe implements PipeTransform {
  transform(date: Date, todayText = 'Today', yesterdayText = 'Yesterday') {
    // TODO: Make today's date mockable, convert to UTC
    const todaysDate = new Date();
    const isToday = areSameDate(todaysDate, date);
    const yesterdaysDate = addDays(new Date(), -1);
    const isYesterday = areSameDate(yesterdaysDate, date);

    const dayText = isToday ? todayText : isYesterday ? yesterdayText : formatDate(date, 'dddd, MMMM, D, YYYY');
    const lastCompletedDate = `${dayText}, ${formatDate(date, 'h:mm A')}`;

    return lastCompletedDate;
  }
}
import { Component, OnInit } from '@angular/core';
import { Routine, RoutinesViewModel } from './models';

@Component({
  selector: 'app-routines',
  templateUrl: './routines.component.html',
  styleUrls: ['./routines.component.css']
})
export class RoutinesComponent implements OnInit {
  private routines: Routine[] = [
    {
      name: 'Morning',
      lastCompletedDate: new Date()
    },
    {
      name: 'Social Media',
      lastCompletedDate: new Date(2017, 8, 23, 19, 55)
    },
    {
      name: 'Bedtime',
      lastCompletedDate: new Date(2017, 8, 5, 21, 16)
    }
  ];

  viewModel: RoutinesViewModel = {
    routines: []
  };

  ngOnInit() {
    this.render();
  }

  trackRoutine(routine: Routine) {
    return routine.name;
  }

  private render() {
    this.viewModel = {
      routines: this.routines
    };
  }
}
<md-toolbar color="primary">
  <span>Routines</span>
</md-toolbar>

<md-nav-list>
  <md-list-item *ngFor="let routine of viewModel.routines; index as i; trackBy: trackRoutine">
    <a>
      <div md-line>
        <span class="mat-title">{{ routine.name }}</span>
      </div>
      <div md-line>
        <span class="mat-subheading-2">{{ routine.lastCompletedDate | todayAwareDate }}</span>
      </div>
    </a>
  </md-list-item>
</md-nav-list>

<a md-fab class="add-routine-button"><md-icon>add</md-icon></a>

There are a couple points to note. First, notice how much less code is in the component. Component code bases can grow very large. If possible, moving mapping logic out of a component generally improves the component's maintainability over time. Second, there used to be two models, one represented the 'entity' or server-side data model and the other represented the model for the view or 'view model'. This distinction may come back later but for now notice that the component no longer must keep track of the date object and the displayed date string. There is just one model, Routine with one date property.

Like how Angular Material creates an NgModule per component, the same convention can be followed for pipes. This is the NgModule for the TodayAwareDatePipe:

import { NgModule } from '@angular/core';

import { TodayAwareDatePipe } from './today-aware-date.pipe';

@NgModule({
  exports: [TodayAwareDatePipe],
  declarations: [TodayAwareDatePipe]
})
export class TodayAwareDateModule { }

It is imported into the RoutinesModule:

// other imports ...
import { TodayAwareDateModule } from '../pipes/today-aware-date.module';

@NgModule({
  declarations: [
    RoutinesComponent
  ],
  imports: [
    CommonModule,
    MdToolbarModule,
    MdListModule,
    MdIconModule,
    MdButtonModule,
    TodayAwareDateModule
  ],
  exports: [
    RoutinesComponent
  ]
})
export class RoutinesModule { }

Tip: Use the Angular v4 TypeScript Snippets Visual Studio Code extension to quickly create both pipes and NgModules.

To view the full repository, check out the branch for this post in the Bebop Routines project on GitHub.

Conclusion

In this example, you saw how to refactor a component's mapping logic to a re-usable pipe. This helps the component's maintainability by reducing both logic and state. Also, the pipe leverages Angular change detection to ensure the mapping logic is only executed when necessary.

Are you using pipes today? How have you found them to be the most useful? Let me know your thoughts and questions in the comments.