Angular中的路由 路由概述 配置路由 路由重定向 路由选中 默认路由(angularjs路由)
1.命令创建项目,不按照依赖:
ng new angualrdemo08 --skip-install安装依赖:cnpm install
2. 创建需要的组件
ng g component home
ng g component news
ng g component newscontent
3. 找到 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'
}
];
4. 找到 app.component.html 根组件模板,配置 router-outlet 显示动态加载的路由
二、Angular routerLink 跳转页面 默认路 由
首页
新闻
//匹配不到路由的时候加载的组件 或者跳转的路由
{
path: '**', /*任意的路由*/
// component:HomeComponent
red
三、Angular routerLinkActive 设 置 routerLink 默认选中路由
.active{
color:red;
}
四、动态路由
1.配置动态路由
const routes: Routes = [
{path: 'home', component: HomeComponent},
{path: 'news', component: NewsComponent},
{path: 'newscontent/:id', component: NewscontentComponent},
{
path: '',
redirectTo: '/home',
pathMatch: 'full'
}
];
2.跳转传值
跳转到详情
跳转到详情
3.获取动态路由的值
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 跳转
1. 引入
import { Router } from '@angular/router';
2.初始化
export class HomeComponent implements OnInit {
constructor(private router: Router) {
}
ngOnInit() {
}
goNews(){
// this.router.navigate(['/news', hero.id]);
this.router.navigate(['/news']);
}
}
3.路由跳转
this.router.navigate(['/news', hero.id]);
六、路由 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);
}
3.获取 get 传值
constructor(private route: ActivatedRoute) {
console.log(this.route.queryParams);
}
七、父子路由
1. 创建组件引入组件
import { NewsaddComponent } from './components/newsadd/newsadd.component';
import { NewslistComponent } from './components/newslist/newslist.component';
2. 配置路由
{
path: 'news',
component:NewsComponent,
children: [
{
path:'newslist',
component:NewslistComponent
},
{
path:'newsadd',
component:NewsaddComponent
}
]
}
3. 父组件中定义 rout
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
暂时没有评论,来抢沙发吧~