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. 禁用nginx的access日志

    修改nginx.conf 找到access_log: access_log /dev/null; 或者access_log off

  2. Java中对List集合的排序

    方法一: 第一种方法,就是list中对象实现Comparable接口,代码如下: 实体类: public class Person implements Comparable<Person> ...

  3. ANDROID_MARS学习笔记_S02_008_ANIMATION第二种使用方式:xml

    一.简介 二.代码1.res\anim下的xml(1)alpha.xml.xml <?xml version="1.0" encoding="utf-8" ...

  4. Android TextView中的ellipsize属性

    TextView中有个ellipsize属性,作用是当文字过长时,该控件该如何显示,解释如下: android:ellipsize=”start”—–省略号显示在开头 android:ellipsiz ...

  5. Android java.net.SocketException四大异常解决方案

    java.net.SocketException如何才能更好的使用呢?这个就需要我们先要了解有关这个语言的相关问题.希望大家有所帮助.那么我们就来看看有关java.net.SocketExceptio ...

  6. S5PV210的IRAM应用

    准备分析   IRAM的大小96k,其实前两个程序都在这里运行的,程序都小于16K.要实现的是从把IRAM从的前16k从IRAM的起始地址0xD0020000拷贝到0xD0024000 处,调用mai ...

  7. 【PythonChallenge】Level 5

    题目主要找发声类似于Peak Hell的Python模块,查了一下手册pickle已经是最像的了.看了一下源代码,发现panner.p.如同发现了新大陆,拷贝内容.使用pickle解答.答案为chan ...

  8. Java Memory Management(1)

    Java Memory Management, with its built-in garbage collection, is one of the language’s finest achiev ...

  9. Cannot proxy target class because CGLIB2 is not available. Add CGLIB to the class path or specify proxy interfaces

    问题解决:缺少jar包 cglib-2.1.3.jar

  10. css3动画(transition)属性探讨

    在webapp引用开发中经常会用到css3动画效果,下面我们就一起探讨一下这个属性的使用. 在哪里定义动画效果? css3动画一般通过鼠标事件或者说状态定义动画,通常我们可以用CSS中伪类和js中的鼠 ...