angular 路由

命令创建项目
  1. 命令创建项目
ng new angualrdemo08 --skip-install
图片.png
  1. 创建需要的组件
ng g component home 
ng g component news 
ng g component newscontent
  1. 找到 app-routing.module.ts 配置路由
  • 引入组件
import { HomeComponent } from './home/home.component';
import { NewsComponent } from './news/news.component'; 
import { NewscontentComponent } from'./newscontent/newscontent.component';
  • 配置路由
const routes: Routes = [ 
{path: 'home', component: HomeComponent}, 
{path: 'news', component: NewsComponent}, 
{path: 'newscontent/:id', component: NewscontentComponent}, 
{ path: '', redirectTo: '/home', pathMatch: 'full' }
 ];
  1. 找到 app.component.html 根组件模板,配置 router-outlet 显示动态加载的路由

首页 新闻

Angular routerLink 跳转页面 默认路由

//匹配不到路由的时候加载的组件 或者跳转的路由 
{ path: '**', /*任意的路由*/ // 
component:HomeComponent,
redirectTo:'home' 
}

设置选中样式

首页 新闻

.active{ color:red; }

动态路由

配置动态路由

const routes: Routes = [ 
{path: 'home', component: HomeComponent}, 
{path: 'news', component: NewsComponent}, 
{path: 'newscontent/:id', component: NewscontentComponent}, 
{ path: '', redirectTo: '/home', pathMatch: 'full' } 
];
//跳转传值
跳转到详情 
跳转到详情

获取动态路由的值

import { ActivatedRoute} from '@angular/router';
constructor( private route: ActivatedRoute) { }
ngOnInit() { 
console.log(this.route.params); 
this.route.params.subscribe(data=>this.id=data.id); 
}

动态路由的 js 跳转

import { Router } from '@angular/router';
export class HomeComponent implements OnInit { 
constructor(private router: Router) { } 
ngOnInit() { }
goNews(){ 
// this.router.navigate(['/news', hero.id]); 
this.router.navigate(['/news']); 
} }

路由 get 传值 js 跳转

  1. 引入 NavigationExtras
import { Router ,NavigationExtras} from '@angular/router';

2.定义一个 goNewsContent 方法执行跳转,用 NavigationExtras 配置传参。

goNewsContent(){ 
let navigationExtras: NavigationExtras = { 
queryParams: { 'session_id': '123' }, 
fragment: 'anchor' 
};
this.router.navigate(['/news'],navigationExtras); }
//获取 get 传值
constructor(private route: ActivatedRoute) { console.log(this.route.queryParams); 
}

父子路由

{ 
path: 'news', 
component:NewsComponent, 
children: [ 
{ path:'newslist', component:NewslistComponent },
{ path:'newsadd', component:NewsaddComponent }
 ] 
}

你可能感兴趣的:(angular 路由)