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. 【无聊放个模板系列】HDU 1358 KMP

    #include<cstdio> #include<cstdlib> #include<cstring> #include<iostream> #inc ...

  2. unity博文搜集

    一.综合篇 1. 脚本 unity3d脚本编程基础 2.Mecanim 使用Mecanim实现连击 3. 数学图形学 U3D需要用到的数学基础  2 4. shader 猫都能学会的Unity3D S ...

  3. S3C2410 实验三——跑马灯实验

    http://www.evernote.com/shard/s307/sh/f2a748e7-34c4-4ce6-acac-82a756cc9e82/ad5813188d655e504857970db ...

  4. JDK版本更换后编译android系统出错

    一:javac: 目标发行版 1.5 与默认的源发行版 1.7 冲突 1.设置jdk环境变量 编译android源码只支持jdk 1.6,所以如果需要编译源码必须下载jdk 1.6,不能下载最新的jd ...

  5. 【HDOJ】1033 Edge

    题目英文太多,简单翻译了一下:1. For products that are wrapped in small packings it is necessary that the sheet of ...

  6. WCF - Hosting WCF Service

    After creating a WCF service, the next step is to host it so that the client applications can consum ...

  7. C++11 中的线程、锁和条件变量

    转自:http://blog.jobbole.com/44409/ 线程 类std::thread代表一个可执行线程,使用时必须包含头文件<thread>.std::thread可以和普通 ...

  8. 用jQuery 处理XML-- jQuery与XML

    jQuery与XML 快而强的遍历系统,华丽丽的选择器语法,这或许是jQuery 那么流行的原因.当然它还有详尽的文档.它主要是用来处理HTML的,但在这里妳会看到如何应用到XML. 使用jQuery ...

  9. jquery如何选择带有多个class的元素

    依次过滤$(“.good”).filter(“.list”).filter(“.Card”) 属性选择$(“[class='good list Card']“);此处 顺序必须一致才行 直接直接用 $ ...

  10. MySql定位执行效率较低的SQL语句

    MySQL能够记录执行时间超过参数 long_query_time 设置值的SQL语句,默认是不记录的. 获得初始锁定的时间不算作执行时间.mysqld在SQL执行完和所有的锁都被释放后才写入日志.且 ...