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

发布时间:2019-06-27 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了angular2 ng2-router 路由,嵌套路由详解脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

实现ng2-router路由,嵌套路由

  1. 首先配置Angular2的时候router模块已经下载,只需要引入即可

    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. 开始配置

    • index.html界面配置两点

      <head>标签中引入 <meta href="/" />
      引入路由代码显示标签 引入主组件标签 <my-app></my-app>

      就这么简单, index.html界面配置完毕

    • @H_304_136@

* 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路由不会进行跳转
    二、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>
 ```

脚本宝典总结

以上是脚本宝典为你收集整理的angular2 ng2-router 路由,嵌套路由详解全部内容,希望文章能够帮你解决angular2 ng2-router 路由,嵌套路由详解所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。