Aurelia Optional Route Parameter

This post expands on the Aurelia post from a couple of weeks ago that involved router links and routing parameters to optional route parameters. The use case for this post is if a user ends up on the contact detail page with no contact ID they will be presented with the option to add a new contact. The starting point for the code can be found here. Keep in mind any changes in this post are taking place in the Aurelia project.

Route with optional parameter

Making a route parameter optional is as simple as adding a question mark to the end of the parameter name. The following is the before and after of the contact detail route found in the  app.ts file in the  ClientApp/app/components/app folder.

For more information on routing see the Aurelia docs.

Contact detail changes

In the contact detail view model which is in the  contactDetail.ts file a class level property is added for if the component was activated with a contact ID or not.

The activate function is changed to set the new class level variable to false if the function is called  parms.id is falsy as well as to only pull contact details if it has a contact ID.

A placeholder for creating a new contact was added to the contact detail view found in contactDetail.html file. This placeholder was added just above the link back to the contact list. This placeholder will only show if the detail components are loaded with no ID.

Add create link to the contact list

Finally, add a link in the  contactList.html file that sends the user to the contact detail view, but without sending a contact ID.

In the example code this was added before the table of contacts, but of course, it could be anywhere.

Wapping up

The code in it’s completed state can be found here. The same functionality using Angular 2 will be coming up next week.

Leave a Reply

Your email address will not be published. Required fields are marked *