The new Angular router – naming conventions

by

This article is very old, and as such do not rely on it for information about the Angular 2.0 router API.

As of this time, the new router has a few naming conventions to be aware of.

Modifying the components directory

I didn’t want to place my components in the root directory of my web application – instead I wanted to stick with a convention where I store all Angular code within an app prefix instead. I then wanted the router to locate my components in app/components instead.

To do this, you need to execute a config method on startup, injecting the $compomentLoaderProvider from the Angular new router. I cloned the dashCase function from the original provider as I just wanted to add a prefix. Seems to me this is harder than it should be, so I’m going to consider opening a case to add a simple setter to configure this.

angular.module('photoreview')
.config(componentLoaderConfig);
function dashCase(str) {
  return str.replace(/([A-Z])/g, function ($1) {
     return '-' + $1.toLowerCase();
  });
}
function componentLoaderConfig($componentLoaderProvider) {
     $componentLoaderProvider.setTemplateMapping(function (name) {
          var dashName = dashCase(name);
          // customized to use app prefix
          return './app/components/' + dashName + '/' + dashName + '.html';
     });
}

Now we can load the components from the app/components directory instead.

Component naming

By default, the router looks for components with the following rules:

  • in the directory structure as ./components using dash-cased names (galleries, edit-gallery)
  • in the route itself with camel casing (editGallery)
  • with the ng-link directive, camel casing as well

You can alias your routes, but it uses this alias for the ng-link name as well as the controller alias name. This doesn’t particularly help situations where you want to use a generic viewmodel name like ‘vm’. I hope we can vary the two independently in the future.

Examples

[table id=1 responsive=”phone” /]