angular2 ng2-router 路由,嵌套路由詳解

實現ng2-router路由,嵌套路由html

  1. 首先配置angular2的時候router模塊已經下載,只須要引入便可bootstrap

    import {RouterModule, Routes} from "@angular/router";
  2. 咱們要建立一個嵌套路由,因此須要建立如下文件瀏覽器

    index.html
    app.module.ts
    app.component.ts
    home.component.ts
    list.component.ts
    list-one.component.ts
    list-two.component.ts
  3. 實現效果:
    路由,單機「首頁」加載home.component.ts
    單機"列表「加載list.component.ts
    列表中包含嵌套路由,tab頁
    單機"標籤一"加載list-one.component.ts
    單機"標籤二"加載list-one.component.ts
  4. 開始配置angular2

    • index.html界面配置兩點app

      <head>標籤中引入 <meta href="/" />
      引入路由代碼顯示標籤 引入主組件標籤 <my-app></my-app>

      就這麼簡單, index.html界面配置完畢this

* app.module.ts界面配置路由
        import {BrowserModule} from "@angular/platform-browser";
        import {NgModule} from "@angular/core";
        import {RouterModule, Routes} from "@angular/router";
    
        // 表單 雙向數據綁定
        import {FormsModule} from "@angular/forms";
        import {AppComponent} from "./app.component";
        // List中包含兩個tab子組件
        import {ListComponent} from "./list.component";
        import {ListOneComponent} from "./list-one.component";
        import {ListTwoComponent} from "./list-two.component";
        import {HomeComponent} from "./home.component";
        // 定義路由, bootstrap默認加載組件就是AppComponent,因此他就是主頁導航頁,而後添加的路由都在他的模板中。
    
        // 能夠全部代碼寫在NgModule中, 也能夠這樣自定義常量,而後使用。
    
        // 定義常量 嵌套自路由
        const appChildRoutes: Routes = [
          {path: "one", component: ListOneComponent},
          {path: "two", component: ListTwoComponent},
          // 若是地址欄中輸入沒有定義的路由就跳轉到one路由界面
          {
            path: '**', redirectTo: "one"
          }
        ];
        // 定義常量 路由
        const appRoutes:Routes = [
          {path: '', component: HomeComponent},
          {
            path: 'list',
            component: ListComponent,
            children: appChildRoutes
        ];
        // 引用定義的路由
        @NgModule({
          imports: [
            BrowserModule,
            FormsModule,
            RouterModule.forRoot(appRoutes)
          ],
          declarations: [
            AppComponent,
            ListComponent,
            HomeComponent,
            ListOneComponent,
            ListTwoComponent
          ],
          bootstrap: [AppComponent]
        })
        export class AppModule {
        
        }
    這樣就完成了嵌套路由的配置
*    顯示路由內容

    * app.component.ts
    
    
        import {Component} from "@angular/core";
        @Component({
          selector: "my-app",
          // templateUrl: "../views/one.html"
          template: `
                    <div>
                    <!--使用了bootstrap樣式的導航,routerLinkActive,表示路由激活的時候,談價active類樣式-->
                    
                    <!--
                    [routerLinkActiveOptions]="{exact: true}" 徹底匹配路由,若是不添加這個,有可能 path="" 會一直添加激活的樣式
                     -->
                    
                      <ul class="nav navbar-nav">
                        <li routerLinkActive="active" [routerLinkActiveOptions]="{exact: true}"><a routerLink="home">首頁</a></li>
                        <li routerLinkActive="active" [routerLinkActiveOptions]="{exact: true}"><a routerLink="contact">聯繫咱們</a></li>
                        <li routerLinkActive="active" [routerLinkActiveOptions]="{exact: true}"><a routerLink="product">產品</a></li>
                      </ul>
                      <!--路由內容顯示區域-->
                      <router-outlet></router-outlet>
                    </div>
                    `
        })
        export class AppComponent {
        
        }
    * list.component.ts

    
    
        import {Component} from "@angular/core";
        @Component({
            selector: "my-list",
            // templateUrl: "../views/list.html"
            template: `
                  <div>
                    <!-- 子路由鏈接 -->
                    <a routerLink="one">one</a>
                    <a routerLink="two">two</a>
                    <!-- 路由內容顯示標籤 -->
                    <router-outlet></router-outlet>
                  </div>
               `
        })
        export class ListComponent {
            name = "list";
        }
                
  
  
 * list-one.component.ts
 
     
    
    
        import {Component} from "@angular/core"
        @Component({
             selector: "my-list-one",
             template:`
                {{name}}
             `
        })
        export class ListOneComponent {
             name = "list-one";
            }

 * list-two.component.ts同理

 ```
 獲取路由參數id  (about:id) 添加模塊 ActivatedRoute
 ```
    
 ```

    import {ActivatedRoute} from "@angular/router";
    
    export class AboutList {
        id: Object;
        constructor(public route:ActivatedRoute) {
            this.id = {};
        }
        ngOnInit() {
            this.route.params.subscribe(params => {
                this.id = params  // {id: "xxx"}
            });
        }
    }
    ----------------------
    路由:
    {
        path: 'contacts-detail/:id',
        component: ContactsDetailComponent
    },
    跳轉
    界面跳轉:
    {{row.instid}}
    <a (click)="contactsCheck(row)"><i class="fa fa-delete"></i>審覈</a>
    <a class="fa fa-editor" [routerLink]="['../contacts-detail/'+ row.instid]">查看詳情</a>
    方法跳轉:
    contactsCheck(value: any) {
    console.log(value);
    this.router.navigate(['./contacts/contacts-detail', value.instid]);
}
    ----------------------
    
    直接獲取id值
    this.route.snapshot.params["id"]
 ```
 
     補助: 路由中的界面跳轉
 ```
     import {Router} from "@angular/router";
     
     constructor(public router: Router) {
     // 至關於window.location.href,界面跳轉
         router.navigateByUrl('home');
     }
 ``` 
 路由跳轉默認以跟路由覺得起點條狀,若是想以當前路由爲起點,設置路由跳轉,添加以下內容
 ```
    import {ActiveRouter, Router} from "router"
    constructor(public acitveRouter: ActiveRouter; public router: Router) {
}

     this.router.navigate(['userList'],{relativeTo: activeRouter}); 
    
    1.this.router.navigate(['user', 1]); 
    以根路由爲起點跳轉
    2.this.router.navigate(['user', 1],{relativeTo: activeRouter}); 
    默認值爲根路由,設置後相對當前路由跳轉,activeRouter是ActivatedRoute的實例,使用須要導入ActivatedRoute
    3.this.router.navigate(['user', 1],{ queryParams: { id: 1 } }); 
    路由中傳參數 /user/1?id=1,查詢參數,用於路由跳轉,返回時候,帶回去一些參數,搜索條件,分頁,等等
    4.this.router.navigate(['view', 1], { preserveQueryParams: true }); 
    默認值爲false,設爲true,保留以前路由中的查詢參數/user?id=1 to /view?id=1
    5.this.router.navigate(['user', 1],{ fragment: 'top' }); 
    路由中錨點跳轉 /user/1#top
    6.this.router.navigate(['/view'], { preserveFragment: true }); 
    默認值爲false,設爲true,保留以前路由中的錨點/user/1#top to /view#top
    7.this.router.navigate(['/user',1], { skipLocationChange: true }); 
    默認值爲false,設爲true路由跳轉時瀏覽器中的url會保持不變,可是傳入的參數依然有效
    8.this.router.navigate(['/user',1], { replaceUrl: true }); 
    未設置時默認爲true,設置爲false路由不會進行跳轉
    2、router.navigate刷新頁面問題
    形成這個問題通常是由於咱們在<form>表單中使用<button>時忘記添加type屬性,在表單中,若是忘記給按鈕添加屬性,會默認爲submit
    ?
    1
    <button (click)="toDetail()">detail</button>
    ?
    1
    2
    3
    toDetail() {
     this._router.navigate(['/detail']);
    }
    解決方法: 
    1.添加type

    <button type="button" (click)="toDetail()">detail</button>
    2.click添加false

    <button (click)="toDetail();false">detail</button>
 ```
相關文章
相關標籤/搜索