Routing in Angular – ASP.NET MVC Application

Now let us see how we can implement routing in Angular – ASP.NET MVC application. This is a continuation of the previous example Creating an Angular – ASP.Net MVC Hybrid Application. You can download the source code from here. In the source code, please refer to 2_Angular_Routing project.

Let us make some changes in application.

First I am going to change the url of the application. For right click on the project -> Select Properties -> Select ‘Web’ from left pane.
Here I added AngularApp at the end of the project url.

Also move angular specific code to a new folder in project root. Below is the new folder structure. All angular related files resides in a folder ‘Angular’.

This requires another change in systemjs.config.js file. Below is the content for updated systemjs,config.js.

If you compare with old systemjs.config.js , you can see that the app folder name is changed and in packages main.js location is also changed.

Edit _Layout.cshtml and add navigation for the application. Here is the content of the file.

Run the application and you can see that four new links are added to the application menu. I have removed About and Contact Us links from the menu.

Create a folder Home in Angular folder and add a new file ‘home.component.ts’. Add below code in the file.

Now add components for the new features in the application, which are Add Employee, List Employees, Add Product and List Products.

Create a folder Employee under Angular and add ‘add-employee.component.ts’ file. Include below code in the file.

Add ‘list-employees.component.ts’ file and add below code in the file.

Create a folder Product in Angular and add ‘add-product.component.ts’ file. Add below code in the file.

Add ‘list-products.component.ts’ and add below code in the file.

Open app.component.ts file in Angular/Common folder and edit template section as shown below.

Add a new file ‘app.routing.ts’ in Angular/Common folder.

Edit app.module.ts and add respective components in declarations. Below is the updated file.

The final folder structure is as shown below.

Run the application and you should see below page.

Navigate to Employee -> Add Employee. If you receive below error then we need to fix one more file.

Open RouteConfig.cs and replace the code as below.

Run the application again. Navigate to Employee\Add Employee.

Navigate to Employee\List Employees

Navigate to Product/Add Product

Navigate to Product/List Products

3 comments on “Routing in Angular – ASP.NET MVC Application”:

Leave a Reply

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