Let's say we have a list of contacts, click each contact, we can render a new route to get the detail.

Define the routers:

//contact-list.router.ts

import {ContactListComponent} from "./contact-list-component.component";
import {ContactDetailComponent} from "./contact-detail-component/contact-detail-component.component";
export const ContactsAppRoutes = [
{ path: '', component: ContactListComponent },
{ path: 'contacts/:id', component: ContactDetailComponent }
];

path: '', --> here empty path means use this component by default.

Bootstrap the router

To use router, we need to provider the router service.

bootstrap(AppComponent, [
provideRouter(ROUTER-OBJECT)
]); 
import { bootstrap } from '@angular/platform-browser-dynamic';
import { enableProdMode } from '@angular/core';
import { AppComponent, environment } from './app/';
import {ContactsAppRoutes} from './app/contact-list-component/contact-list.routes';
import {provideRouter} from "@angular/router"; if (environment.production) {
enableProdMode();
} bootstrap(AppComponent, [
provideRouter(ContactsAppRoutes)
]);

Create outlet for rendering the router:

//app.component.html

<h1>
{{title}} Hello Router 3.0
</h1>
<router-outlet></router-outlet>

So the router will be render inside this router-outlet.

The contact list component:

import { Component, OnInit } from '@angular/core';
import {ContactDetailComponent} from "./contact-detail-component/contact-detail-component.component";
import {ROUTER_DIRECTIVES} from "@angular/router"; @Component({
moduleId: module.id,
directives: [ContactDetailComponent, ROUTER_DIRECTIVES],
selector: 'app-contact-list-component',
templateUrl: 'contact-list-component.component.html',
styleUrls: ['contact-list-component.component.css']
})
export class ContactListComponent implements OnInit { contacts: Array<Object>;
constructor() {
this.contacts = [
{
id: 0,
name: "Zhentian",
position: "Lead developer"
},
{
id: 1,
name: "ABC",
position: "Junior developer"
},
{
id: 2,
name: "Herry",
position: "Productor Owner"
},
{
id: 3,
name: "Janne",
position: "Master"
},
{
id: 4,
name: "Jonne",
position: "Backend developer"
}
];
}
ngOnInit() {
} }

Notice that, we have inject the ROUTER_DIRECTIVE for later use.

Template for the contact list component:

<h2>Contacts</h2>
<ul>
<li *ngFor="let contact of contacts">
<a [routerLink]="['/contacts', contact.id]">{{contact.name}}</a> |
<a routerLink="/contacts/{{contact.id}}">{{contact.name}}</a>
</li>
</ul>

To navigate to other router compoent, we need to use 'routerLink', notice there is tow ways to use 'routerLink':

<a [routerLink]="['/contacts', contact.id]">{{contact.name}}</a> 

or

<a routerLink="/contacts/{{contact.id}}">{{contact.name}}</a>

For the contact detail compoent, we want to receive an 'id', which can later fetch the data from server.

To get the param which be passed in , we need to use 'ActivedRoute':

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router'; @Component({
moduleId: module.id,
selector: 'app-contact-detail-component',
templateUrl: 'contact-detail-component.component.html',
styleUrls: ['contact-detail-component.component.css']
})
export class ContactDetailComponent implements OnInit { id: number;
constructor(private route: ActivatedRoute) {
this.id = this.route.snapshot.params['id'];
} ngOnInit() {
} }

Here we use 'snapshot', this means we don't care about the later router params changes, we just need to get id and that's it. It is a cheaper solution.

Another way to do it is using ObservableActivatedRoute comes with a params property which is an Observable. To access the contact id, all we have to do is to subscribe to the parameters Observablechanges.

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router'; @Component({
moduleId: module.id,
selector: 'app-contact-detail-component',
templateUrl: 'contact-detail-component.component.html',
styleUrls: ['contact-detail-component.component.css']
})
export class ContactDetailComponent implements OnInit { id: number;
constructor(private route: ActivatedRoute) {
} ngOnInit() {
this.route.params
.map(params => params['id'])
.subscribe((id) => {
this.id = id;
});
} }

But in this case, use snapshot is prefect fine, since id would change later.

Original Actical: http://blog.thoughtram.io/angular/2016/06/14/routing-in-angular-2-revisited.html

Github: https://github.com/zhentian-wan/hello-angular2

[Angular 2] ROUTING IN ANGULAR 2 REVISITED的更多相关文章

  1. 关于Angular.js Routing 的学习笔记(实现单页应用)

    最近开始学习angular.js,发现angular.js确实很方便,也很强大.在看到 AngularJS Routing and Multiple Views 这一部分的时候,有点乱.现在通过记录一 ...

  2. Angular学习笔记:Angular CLI

    定义 Angular CLI:The Angular CLI is a command line interface tool that can create a project, add files ...

  3. angular enter事件,angular回车事件

    angular回车键搜索,angular enter搜索 对于搜索框,用户在输入内容后的搜索习惯不是鼠标点击搜索按钮,而是直接按enter键,那我们怎么给enter键绑定事件呢,其实很简单,代码如下: ...

  4. Angular 2 升级到 Angular 5

    Angular 2 升级到 Angular 5 ts文件最上面的import语句里不要添加 .ts 后缀 , 不然 npm start 编译会失败 . 虽然浏览器能打开项目的URL , 但是内容会丢失 ...

  5. Angular系列一:Angular程序架构

    Angular程序架构 Angular程序架构 组件:一段带有业务逻辑和数据的Html服务:用来封装可重用的业务逻辑指令:允许你向Html元素添加自定义行为模块: 环境搭建 安装nodeJs安装好no ...

  6. Part 23 to 26 Routing in Angular

    Part 23 AngularJS routing tutorial In general, as the application becomes complex you will have more ...

  7. Angular - 预加载 Angular 模块

    Angular - 预加载延迟模块 在使用路由延迟加载中,我们介绍了如何使用模块来拆分应用,在访问到这个模块的时候, Angular 加载这个模块.但这需要一点时间.在用户第一次点击的时候,会有一点延 ...

  8. Angular企业级开发(3)-Angular MVC实现

    1.MVC介绍 Model-View-Controller 在20世纪80年代为程序语言Smalltalk发明的一种软件架构.MVC模式的目的是实现一种动态的程序设计,使后续对程序的修改和扩展简化,并 ...

  9. 30行代码让你理解angular依赖注入:angular 依赖注入原理

    依赖注入(Dependency Injection,简称DI)是像C#,java等典型的面向对象语言框架设计原则控制反转的一种典型的一种实现方式,angular把它引入到js中,介绍angular依赖 ...

随机推荐

  1. [jobdu]二叉树的镜像

    树的镜像,这里的做法就是先序遍历的反过来呗. #include <iostream> #include <vector> using namespace std; void p ...

  2. Altium Designer中默认取消重复画线的选项

  3. More on 1Password’s Components

    Stefan van As of 1Password fame sent me a more exhaustive list of the libraries and tools used in 1P ...

  4. Android Service的生命周期

    service的生命周期,从它被创建开始,到它被销毁为止,可以有两条不同的路径: A started service 被开启的service通过其他组件调用 startService()被创建. 这种 ...

  5. rc522 ,pn544区别

    请问 我们之前用的刷卡的  是用 rc522  ,,pn544和这个有什么区别? xqhrs232 (10:14:27): 支持的协议更多点吧! 春tian在哪里 (10:14:38): 比如? xq ...

  6. 存储过程系列之存储过程具体操作过程及sql数据库调用

    Transact-SQL中的存储过程,非常类似于Java语言中的方法,它可以重复调用.当存储过程执行一次后,可以将语句缓存中,这样下次执行的时候直接使用缓存中的语句.这样就可以提高存储过程的性能. 存 ...

  7. poj3280Cheapest Palindrome(记忆化)

    链接 真的1A了.. 一开始想复杂了 想着补全再删 没想好 后来想到递归 大的回文串是由小的推过来的 一直递归下去 对于当前的i,j可以选择保留或者删除 选个最小的 #include <iost ...

  8. ☀【css】透明

    让IE浏览器支持RGBA颜色http://www.hujuntao.com/web/css/ie-browser-support-for-rgba-color.html 透明纯色背景 backgrou ...

  9. aspx页面记住密码

    界面 点击登录按钮的代码 protected void btnLogin_Click(object sender, EventArgs e) { if (remember_long.Checked) ...

  10. 使用C#调用Python脚本,带参数列表 z

    static void Main(string[] args) { string[] strArr;//参数列表 string sArguments = @"Pythons.py" ...