首頁  >  文章  >  web前端  >  詳解Angular中的路由及其用法

詳解Angular中的路由及其用法

青灯夜游
青灯夜游轉載
2021-03-03 10:01:481754瀏覽

本篇文章帶大家來了解Angular中的路由,以及Angular路由的使用。有一定的參考價值,有需要的朋友可以參考一下,希望對大家有幫助。

詳解Angular中的路由及其用法

相關推薦:《angular教學

一、

1、指令建立專案

ng new ng-demo --skip-install

詳解Angular中的路由及其用法

2、建立需要的元件

ng g component components/home
ng g component components/news
ng g component components/newscontent
3、找到app-routing.module.ts 設定路由


引入元件

import { HomeComponent } from './components/home/home.component';
import { NewsComponent } from './components/news/news.component';
import { ProductComponent } from './components/product/product.component';
設定路由

const routes: Routes = [
{path: 'home', component: HomeComponent},
{path: 'news', component: NewsComponent},
{path:'product', component:ProductComponent },
{path: '*', redirectTo: '/home', pathMatch: 'full' }
];
4、找到app.component .html 根元件模板,設定router-outlet 顯示動態載入的路由

<h1>
    <a>首页</a>
    <a>新闻</a>
</h1>
<router-outlet></router-outlet>

#二、Angular routerLink 跳轉頁面預設路由
<a>首页</a>
<a>新闻</a>
//匹配不到路由的时候加载的组件 或者跳转的路由
{
    path: '**', /*任意的路由*/
    // component:HomeComponent
    redirectTo:'home'
}

三、Angular routerLinkActive 設定routerLink 預設選取路由
<h1>
  <a>
    首页
  </a>
  <a>
    新闻
  </a>
</h1>
<h1>
    <a>首页</a>
    <a>新闻</a>
</h1>

#四、動態路由

4.1.問號傳參

#跳轉方式,頁面跳到或js跳到

問號傳參的url位址顯示為…/list-item?id=1

queryParams屬性是固定的

{
{ item.name }}

#//js跳轉

//router為ActivatedRoute的實例

import { Router } from '@angular/router';
.
constructor(private router: Router) {}
.
this.router.navigate(['/newscontent'],{
  queryParams:{
    name:'laney',
    id:id
  },
  skipLocationChange: true 
  //可以不写,默认为false,设为true时路由跳转浏览器中的url会保持不变,传入的参数依然有效
});
取得參數方式

import { ActivatedRoute } from '@angular/router';

constructor(public route:ActivatedRoute) { }
ngOnInit() { 
    this.route.queryParams.subscribe((data)=>{
      console.log(data);
 })
}

4.2 路徑傳參

#路徑傳參的url位址顯示為…/list-item/1

<a [routerLink]="[’/list-item’, item.id]"> {{ item.name }}
//js跳转 //router为ActivatedRoute的实例
this.router.navigate([’/list-item’, item.id]);

路徑配置:


{path: ‘list-item/:id’, component: ListItemComponent}

取得參數方式

this.route.params.subscribe(
  param => {
      this.id= param['id'];
  }
)

五、父子路由

1、建立元件引入元件

import { WelcomeComponent } from ‘./components/home/welcome/welcome.component’;
 import { SettingComponent } from ‘./components/home/setting/setting.component’;

2、設定路由

{
    path:'home',
    component:HomeComponent,
    children:[{
      path:'welcome',
      component:WelcomeComponent
    },{
      path:'setting',
      component:SettingComponent
    },
    {path: '**', redirectTo: 'welcome'}
  ]
},
3、父元件中定義router-outlet

更多程式相關知識,請造訪:

程式設計影片! !

以上是詳解Angular中的路由及其用法的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:csdn.net。如有侵權,請聯絡admin@php.cn刪除