angular 配置路由 路由重定向 路由选中 默认路由的方法
dearweb
发布:2021-08-29 20:25:55阅读:
今天主要与大家分享angular 配置路由 路由重定向 路由选中 默认路由的方法,非常重要,可以说如果你不会路由,项目则不能独立完成。
路由的定义
路由是根据不同的url地址,动态的让根组件挂载其他组件来实现一个单页面的应用。
创建项目
创建一个项目,带路由
ng new angularrouter --skip-install //是否选择路由的时候,输入y ? Would you like to add Angular routing? (y/N) y //选择对应的css 预处理器 ? Which stylesheet format would you like to use? CSS > SCSS [ https://sass-lang.com/documentation/syntax#scss ] Sass [ https://sass-lang.com/documentation/syntax#the-indented-syntax ] Less [ http://lesscss.org
创建路由所需组件
PS D:\angular\ngRouter> ng g component components/home PS D:\angular\ngRouter> ng g component components/news PS D:\angular\ngRouter> ng g component components/product
配置路由以及路由重定向
// 配置路由
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
// 引入组件
import {HomeComponent} from '../app/components/home/home.component'
import {NewsComponent} from '../app/components/news/news.component'
import {ProductComponent} from '../app/components/product/product.component'
const routes: Routes = [
{
path:'home',
component:HomeComponent
},
{
path:'news',
component:NewsComponent
},
{
path:'product',
component:ProductComponent
},
// 匹配不到路由跳转到home
{
path:'**',
redirectTo:'home'
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }路由跳转以及路由的选中
找到app.component.html 根组件模板,配置router-outlet 显示动态路由使用 routerLink实现路由跳转,使用routerLinkActive属性
<a routerLink="/home" routerLinkActive="active">首页</a> <a routerLink="/news" routerLinkActive="active">新闻</a> <a routerLink="/product" routerLinkActive="active">项目</a>
小礼物走一波,支持作者
赏还没有人赞赏,支持一波吧