文章16 | 阅读 6583 | 点赞0
ng new ng-demo --skip-install
ng g component components/home
ng g component components/news
ng g component components/newscontent
引入组件
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' }
];
<h1>
<a routerLink="/home">首页</a>
<a routerLink="/news">新闻</a>
</h1>
<router-outlet></router-outlet>
<a routerLink="/home">首页</a>
<a routerLink="/news">新闻</a>
//匹配不到路由的时候加载的组件 或者跳转的路由
{
path: '**', /*任意的路由*/
// component:HomeComponent
redirectTo:'home'
}
<h1>
<a routerLink="/home" routerLinkActive="active">
首页
</a>
<a routerLink="/news" routerLinkActive="active">
新闻
</a>
</h1>
<h1>
<a [routerLink]="[ '/home' ]" routerLinkActive="active">首页</a>
<a [routerLink]="[ '/news' ]" routerLinkActive="active">新闻</a>
</h1>
跳转方式,页面跳转或js跳转
问号传参的url地址显示为 …/list-item?id=1
queryParams属性是固定的
<a [routerLink]="[’/list-item’]" [queryParams]="{id:item.id}">
{{ 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);
})
}
路径传参的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'];
}
)
import { WelcomeComponent } from ‘./components/home/welcome/welcome.component’;
import { SettingComponent } from ‘./components/home/setting/setting.component’;
{
path:'home',
component:HomeComponent,
children:[{
path:'welcome',
component:WelcomeComponent
},{
path:'setting',
component:SettingComponent
},
{path: '**', redirectTo: 'welcome'}
]
},
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://codeboy.blog.csdn.net/article/details/107852357
内容来源于网络,如有侵权,请联系作者删除!