Angular 2

Custom Pipes in Angular 2

I am working on a project that is using an ASP.NET Core web API to return JSON that is then used by Angular 2. The dates that needed to be formatted before being shown to the user which lead me to pipes.

Pipes

In Angular 2 pipes are away to apply some transformation on a field before its value is displayed to the user. Some common pipes are provided out of the box for things like numbers, dates and percentages.

For the following example created  is a property for the date a contact was added. To have created just display the month, date and year the date pipe will be used with the short date format.

{{contact.created | date: 'shortDate'}}

The above is standard Angular 2 binding  with an added pipe “|” followed by the name of the pipe which in this case is date. The built-in date pipe can take arguments for how to the date should be formatted. If the created date was today than the resulting output of the above binding would be 4/10/2016. For a full list of built-in formats see the Angular docs.

The Problem

I added the date pipe to the fields that needed formatting and ran the app. Instead of the formatted date I was expecting I got a partially rendered page. A quick peek in Chrome’s dev tools showed the following exception.

EXCEPTION: Invalid argument ‘2016-04-10T08:00:00’ for pipe ‘DatePipe’ in [{{contact.created | date: ‘shortDate’}}

Turns out that the date pipe only works if the value it is processing is a number or a date. I found this out by looking at the code for the date pipe which can be found here. My created property came from JSON which doesn’t have a way to denote something as a date. This means the created property is actually a string instead of a date..

Solution 1 – Convert to a date

One way to fix this issue is to use the string representation of the date to create a new date and assign it over the top of the existing property. For example:

contact.created = new Date(contact.created);

After the above is applied to all the dates that need formatted Angular’s date pipe can be used with no problems.

Solution 2 – Custom pipe

I decided to try writing a custom pipe that would take a string that should be a date and format it if it is actually date using Angular’s date pipe.  The following is the resulting pipe.

import {Pipe, PipeTransform} from 'angular2/core';
import {DatePipe} from 'angular2/common';

@Pipe({ name: 'dateString' })
export class DateString implements PipeTransform {
    transform(value: string, args: any[]): string {
        var parsedDate = Date.parse(value);
        if (isNaN(parsedDate)) {
            return "";
        }
        else {
            return new DatePipe().transform(new Date(parsedDate), args);
        }
    }
}

First Pipe and PipeTransform are imported. The class must be decorated with @Pipe which is also used to give the pipe its name. The class must also implement PipeTransform which defines a transform function.

The transform function is where all the work happens. It takes a value and formatting arguments and return the value that should be displayed. In my case the value is parsed to a date which returns the number of milliseconds since January 1, 1970 00:00:00 UTC or not a number if parsing fails for some reason. For the not a number result an empty string will be return and displayed to the user.

In the case the date is value then a new instance of Angular’s date pipe is created it handles formatting using the new date value which is then return and displayed for the user. In order to use Angular’s date pipe inside my custom pipe it needed to be imported as well.

Custom Pipe Usage

To use a custom pipe it must be imported by the view model class of the view that needs formatted.

import { DateString } from './dateString.pipe';

Then it must be added to the component decorator.

@Component({
    selector: 'viewContacts',
    templateUrl: 'viewContacts.component.html',
    pipes: [DateString]
})

The view will now be able to use the pipe. The syntax is the same as built-in pipes just with the name provided in the pipe decorator which is dateString in this example.

{{contact.created | dateString: 'shortDate'}}

Suggestions

The above are two of the solutions I came up with when I had problems with Angular’s built in date pipe. They are by no means the only options. If you have a suggestion on a better way to handle dates coming from JSON please leave a comment.

Also note that there is an issue logged on the Angular repo to support strings in the built in date pipe which can be found here.

Custom Pipes in Angular 2 Read More »

Migration from Angular 2 Beta 3 to Beta 7

I was recently working on getting Angular 2 up and running in a new project and hit some issues getting typescript to compile. I had been using beta 3 on samples for this blog.  The issues I was having are with typescript trying to build and resulting in multiple TS2304 errors similar to “Build: Cannot find name ‘x'”.

I am going to go over the update process first and then the fix for the typescript build issue.

Upgrade

In the dependencies section of the project’s package.json file the following versions need to be updated to the versions listed.

"dependencies": {
  "angular2": "2.0.0-beta.7",
  "systemjs": "0.19.22",
  "es6-promise": "^3.1.2",
  "es6-shim": "^0.33.4",
  "reflect-metadata": "0.1.2",
  "rxjs": "5.0.0-beta.2",
  "zone.js": "0.5.15"
}

Not a lot of changes, but this is also the point that the build typescript build errors kick in. This reference application I found from Dan Wahlin was a huge help it tracking down what the issue was.

Fixing TS2304 Errors

The errors I was getting related mostly to promise and map which turns out to be related to es6-shim. Turns out this issues can be fixed by adding a typings references for es6-shim.

In package.json add a reference to typings in the devDependencies section. Here is an example from my project.

"devDependencies": {
  "es6-module-loader": "^0.17.8",
  "gulp": "3.8.11",
  "gulp-concat": "2.5.2",
  "gulp-cssmin": "0.1.7",
  "gulp-uglify": "1.2.0",
  "rimraf": "2.2.8",
  "jspm": "0.16.15",
  "typings": "^0.6.8"
}

Next from a console run typings init  to get typings setup for the project. This adds a typings.json file. If you are already using typing this step can be skipped. If you were previously using TSD then make sure to check out the typings upgrade command handle converting your project to the new format.

Now the typing for es6-shim can be installed by running typings install es6-shim –ambient –save in the console.

Finally add two new lines to the exclude section of the tsconfig.json file for main and main.d.ts. This prevents duplicate identifier errors.

"exclude": [
  "node_modules",
  "typings/main",
  "typings/main.d.ts"
]

After the above changes the project is now running on beta 7 of Angular 2. I updated the reference application on GitHub with the changed from this post and which can be found here.

If you hit any issues during your upgrade to beta 7 please leave a comment.

Migration from Angular 2 Beta 3 to Beta 7 Read More »