Click here to Skip to main content
13,860,571 members
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

22.7K views
8 bookmarked
Posted 9 Jan 2017
Licenced Apache

Angular2 - Routing

, 14 Jan 2017
Rate this:
Please Sign up or sign in to vote.
What is routing?Routing is mechanism used by angular for navigating between page and displaying appropriated component/page on browser.I was confused, can you explain more in detail?ok, With our code, when you type on address bar this URI "http://localhost/users".Angular will look for the component

What is routing?

Routing is mechanism used by angular for navigating between page and displaying appropriated component/page on browser.

I was confused, can you explain more in detail?

ok, With our code, when you type on address bar this URI "http://localhost/users".

Angular will look for the component (or web page) will be rendered on browser based on information which was registered.

Which information do we need to register to Angular in order to view "http://localhost/users"?

Please checkout the code from "https://github.com/techcoaching/angular2.git".

Open "<root>/src/userRoutes.ts", we see the code as below:

import { NgModule } from "@angular/core";
import { RouterModule, Routes } from "@angular/router";
import { Users } from "./users";
import { CreateUser } from "./createUser";

let routes: Routes = [
    { path: 'users', component: Users },
    { path: 'createUser', component: CreateUser }
];
@NgModule({
    imports: [RouterModule.forRoot(routes)],
    exports: [RouterModule]
})
export class UserRoutes { }

In this code, we register to Angular, When user access to "<baseUrl>/users", Users component will be rendered on browser. baseUrl="http://localhost/" in this case.

{ path: 'users', component: Users },

On the browser, the content was rendered as photo below:
 

I want the application redirects to "http://localhost/users" when user browses to "http://localhost", can I do that?

Yes, we can, Please add this route config into the the list of route configurations:

{ path: "", redirectTo: "/users", pathMatch: 'full' }

userRoute.ts will be:

let routes: Routes = [
    { path: "", redirectTo: "/users", pathMatch: 'full' },
    { path: 'createUser', component: CreateUser },
    { path: 'users', component: Users }
    
];
@NgModule({
    imports: [RouterModule.forRoot(routes)],
    exports: [RouterModule]
})
export class UserRoutes { }

 When I run "http://localhost", the system redirects to "http://localhost/users", then i got "HTTP Error 404.0 - Not Found" when refreshing the browser, My app was deployed on IIS?

Yes, Please help me to check if we have "web.config" file at root folder of the app. Missing this file will raise this type of error.

Why do I need web.config file, I did not use any server code?

Browsing to "http://localhost/users" will trigger default handler on IIS and there is not content mapped to that URI. That is why the browser display "HTTP Error 404.0 - Not Found"

<rewrite>
	<rules>
		<rule name="Rewrite to default" enabled="true" stopProcessing="true">
			<match url="^[^.]+$" />
			<action type="Rewrite" url="/" />
		</rule>
	</rules>
</rewrite>

In Web.Config, it will auto rewrite the current request to "index.html" file (default page of IIS), this is where angular handles the "/users" path using registered route configuration.

I got error as photo below when removing <base href="http://www.tranthanhtu.vn/"/>  from index.html file, what is this?

This is html tag, for more information, see HTML <base> Tag

In general, the browser use this for identifying the location of resources will be loaded.

By default we use <base href="http://www.tranthanhtu.vn/"/>

It seems the whole web-page was reloaded when I navigate between "Users" and "Add new User"?

Yes, look at layout.html, Link to "Users" and "Add new User" are pure HTML attributes.

Please change them to:

Now, let try to click on these link again, the navigation between pages looks nicer.

Can I move the region of page content will be displayed to other location?

In layout.html, we can move the "router-outlet" tag to appropriated location.

The content on browser will be changed also:

Can I pass parameter from 1 page to another page and how can I do that?

Yes, You can. Let add new route config into UserRoutes.ts:

{ path: 'editUser/:id', component: CreateUser }

In constructor function of CreateUser:

export class EditUser{
    constructor(route: ActivatedRoute){
        console.log("User selected:", route.params.value.id);
    }
}

Instance of ActivatedRoute will be passed into the constructor of CreateUser by Angular using Dependency Inject (or DI in short) mechanism (We will talk about DI later).

We can get the value of passing parameter by: route.params["value"].<name of parameter in route config>. For example: route.params["value"].id will return id of selected user.

How can I navigate between page from my code?

Let add some html into users.html as below:

<div>
	<table class="table">
		<thead>
			<tr>
				<th>#</th>
				<th>First Name</th>
				<th>Last Name</th>
				<th>Username</th>
				<th>Action</th>
			</tr>
		</thead>
		<tbody>
			<tr>
				<th scope="row">1</th>
				<td>TU</td>
				<td>Tran</td>
				<td>@tutran</td>
				<td>
					<a (click)="onEditClicked(1)" title="Edit tutran"><i class="fa fa-edit"></i></a>
				</td>
			</tr>
			<tr>
				<th scope="row">2</th>
				<td>TU</td>
				<td>Tran 1</td>
				<td>@tutran1</td>
				<td>
					<a (click)="onEditClicked(2)" title="Edit tutran1"><i class="fa fa-edit"></i></a>
				</td>
			</tr>
			<tr>
				<th scope="row">3</th>
				<td>TU</td>
				<td>Tran 2</td>
				<td>@tutran2</td>
				<td>
					<a (click)="onEditClicked(3)" title="Edit tutran3"><i class="fa fa-edit"></i></a>
				</td>
			</tr>
		</tbody>
	</table>
</div>

In Users class, we add "onEditClicked" handler as below:

import { Component } from "@angular/core";
import { Router } from "@angular/router";
@Component({
    selector: "users",
    templateUrl: "src/users.html"
})
export class Users {
    private router: Router;
    constructor(router: Router) {
        this.router = router;
    }
    public onEditClicked(userId: string) {
        this.router.navigate(["/editUser", userId])
    }
}

In the code, we use router.navigate function to navigate to "editUser" page:

this.router.navigate(["/editUser", userId])

Base on the route configuration in userRoutes.ts:

{ path: 'editUser/:id', component: EditUser }

What can I do if I have more than 1 parameter?

we register route configuration:

{ path: 'editUser/:id1/:id2', component: EditUser }

And navigate using router.navigate function as below:

this.router.navigate(["/editUser", "value-of-id1", "value-of-id2"])

Can I specify optional  parameters in route configuration?

No at this time, all parameters are required. We can define multiple routes with different parameters as:
let routes: Routes = [
    { path: "", redirectTo: "/users", pathMatch: 'full' },
    { path: 'addNewUser', component: CreateUser },
    { path: 'editUser/:id', component: EditUser },
    { path: 'editUser/:id1/:id2', component: EditUser },
    { path: 'users', component: Users }
];

Using multiple routes with different parameters will create duplicated route configuration, is there any other solution for this?

I totally agree, this leads to many similar route configurations and raises other issues related to maintenance.

For optional parameters, we should pass them as query parameters. This is the correct use.

For example, In our case, id is required parameter and id1 is optional. We only need to register route config for this as:

{ path: 'editUser/:id', component: EditUser }

userRoutes.ts will be:

let routes: Routes = [
    { path: "", redirectTo: "/users", pathMatch: 'full' },
    { path: 'addNewUser', component: CreateUser },
    { path: 'editUser/:id', component: EditUser },
    { path: 'users', component: Users }
];

In Users.ts, we navigate to "Edit User" page:

public onEditClicked(userId: string) {
	this.router.navigate(["/editUser", userId,{id1:"optional-parameter"}])
}

Note: Query parameters were passed as JSON object.

In EditUser.ts, we get back values of those and print to console:

export class EditUser{
    constructor(route: ActivatedRoute){
        let requiredIdparam=route.params["value"].id;
        let optionalIdparam=route.params["value"].id1;
        console.log("User selected:", requiredIdparam, optionalIdparam);
    }
}

The result in browser as below:

Thank for reading

License

This article, along with any associated source code and files, is licensed under The Apache License, Version 2.0

Share

About the Author

tranthanhtu.vn
Architect
Vietnam Vietnam
I have more than 8 years in web development for multiple types of applications (ERP, Education System, ...).
I usually organize training/ coaching on specified topic (such as: RESTful/ WebApi, Angular2, BEM, LESS, SASS, EF, NodeJs ....). Please contact me on Skype (tranthanhtu83) or email (contact@tranthanhtu.vn) if need.
For more information about me, Please visit http://www.tranthanhtu.vn/page/about-me

You may also be interested in...

Comments and Discussions

 
Questionnested modules Pin
Abolfazl RoshanZamir3-Apr-18 6:41
memberAbolfazl RoshanZamir3-Apr-18 6:41 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web05 | 2.8.190214.1 | Last Updated 14 Jan 2017
Article Copyright 2017 by tranthanhtu.vn
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid