Angular2 basic routing

Home / Angular2 basic routing

In continuing to build upon my previous project to get Angular2 working with Visual Studio 2015, I’ve been playing with routing and components.

While routing and components are very different when compared to Angular v1, it’s still pretty straight forward to get a basic application up and running.


Since the previous test project is using the default VS2015 tempaltes, it made sense to play around with changing the basic layout to be Angular(2) aware. The default layout has a menu bar with (3) distinct links:

To “angularize” the app, I thought it would be nice and illustrative to componentize the three basic menu items with routes and components. So, let’s jump right in.

First, we lets define some routes. Our routes.ts file will look like this:

import { provideRouter, RouterConfig } from '@angular/router';
import { ContactComponent }  from './contact.component';
import { HomeComponent }  from './home.component';
import { AboutComponent }  from './about.component';

const routes: RouterConfig = [
    { path: '', component: HomeComponent },
    { path: 'about', component: AboutComponent },
    { path: 'contact', component: ContactComponent }
];

export const appRouterProviders = [
    provideRouter(routes)
];

By defining this routes.ts file, we have defined our paths and which components will serve for those paths. The components themselves are simple. I’ve defined all (3) of them in the same manner by creating the appropriately named TypeScript file:

import { Component } from '@angular/core';
@Component({
    templateUrl: "/home/HomeComponent"
})
export class HomeComponent { }

You can see my components are doing nothing more than defining a templateUrl. The templates in turn will be loaded from the HomeController:

public IActionResult MainComponent()
{
    return View();
}

public IActionResult AboutComponent()
{
    return View();
}

public IActionResult HomeComponent()
{
    return View();
}

public IActionResult ContactComponent()
{
    return View();
}

The main.ts that we previously referenced has to be changed slightly to reference our templateUrl and to import/use the ROUTER_DIRECTIVES:

/// <reference path="../typings/globals/es6-shim/index.d.ts" />
import { Component } from "@angular/core";
import { ROUTER_DIRECTIVES } from '@angular/router';

@Component({
    selector: "app-shell",
    templateUrl: "/home/MainComponent",
    directives: [ROUTER_DIRECTIVES]
})

export class Main {
    title: string;
    constructor() {
        this.title = "World!";
    }
}

The final JavaScript change that we have to make is for the bootstrapper.ts. This TypeScript file has to be made aware of our application routing.

import { bootstrap }    from "@angular/platform-browser-dynamic";
import {ROUTER_DIRECTIVES}  from "@angular/router";

import {Main} from "./main";
import { appRouterProviders } from './routes';

bootstrap(Main, [appRouterProviders]);

The main component’s template now will own the menu navigation links. Basically, all I have done is hacked apart the original _Layout.cshtml and Index.cshtml to split things apart. The MainComponent.cshtml will now look like the below template. You can see that the primary change is to specifify our router links and define the special “router-outlet” HTML element. Angular2 uses this element to know where to inject the HTML for a component to which we have been routed. It is synonymous with the old ui-router’s “ui-view”.

@{
    Layout = null;
}

<div class="navbar navbar-inverse navbar-fixed-top">
    <div class="container">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a asp-area="" asp-controller="Home" asp-action="Index" class="navbar-brand">MyTestApp</a>
        </div>
        <div class="navbar-collapse collapse">
            <ul class="nav navbar-nav">
                <li><a [routerLink]="['/']">Home</a></li>
                <li><a [routerLink]="['/about']">About</a></li>
                <li><a [routerLink]="['/contact']">contact</a></li>
            </ul>
        </div>
    </div>
</div>
<div class="container body-content">
    <router-outlet></router-outlet>
    <hr />
    <footer>
        <p>&copy; 2016 - MyTestApp</p>
    </footer>
</div>

I won’t bore you with the Home/About/Contact component template’s. These are all copy/paste versions of the original *.cshtml files. I haven’t put this project into a public Github repository yet, but will shortly.

UPDATE: Github source added.

https://github.com/long2know/angular2-simple-routing

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.