Angular2之路由學習筆記

目前工做中項目的主要技術棧是Angular2 在這裏簡單記錄一下遇到的問題以及解決方案。html

這篇筆記主要記錄Angular2 的路由。瀏覽器

官方文檔連接:https://angular.cn/docs/ts/latest/guide/router.html  (中文版)ide

https://angular.io/docs/ts/latest/guide/router.html (英文原版)ui

這裏講的路由主要是應用於頁面間的跳轉。this

1.最經常使用最簡單的spa

<a routerLink="/heroes" routerLinkActive="active">Heroes</a>

routerLink屬性,點擊a標籤後直接跳轉到"/heroes"。這裏不必定是a標籤,也能夠是button、div等等。code

routerLinkActive屬性,不是必須,該屬性值爲一個CSS類名。做用是當路由跳轉到"/heroes"後,給該a標籤增長該"active"樣式。通常用於以下場合,「隨筆」就自動增長了"active"樣式router

 2.後退htm

通常的瀏覽器都有後退功能,但也能夠本身寫一個,統一風格。blog

import { Location } from '@angular/common';

export class Back {
  constructor(private location: Location) {
  }

  back() {
    this.location.back();
  }

}

而後在html中寫個(click) =  "back()"便可

3.不少時候,場景、需求決定了不能在html中使用routerLink。須要執行一些js邏輯程序後再跳轉。

import { Router } from '@angular/router';
export class RouteComponent {

  constructor(private router: Router) {
  }
 
jump(){
this.router.navigate(["/hero"]);
 }

 jump1(){
 
this.router.navigateByUrl("/home/hero");
}
}
相關文章
相關標籤/搜索