今天来个大家分享angular路由跳转的方法,话不多说直接上代码:
a标签进行跳转:
1,创建组件ng g c home
, ng g c news
, ng g c product
2,将组件引入到根组件中,并在declarations
中进行配置。(如果是通过命令生成组件,原则上会配置,但需要检查一下)
import { NewsComponent } from './components/news/news.component';
import { HomeComponent } from './components/home/home.component';
import { ProductComponent } from './components/product/product.component';
declarations: [
AppComponent,
NewsComponent,
HomeComponent,
ProductComponent
],
3,在路由配置文件中引入我们创建的组件,在routes
对象中配置路由。
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 },
];
4,配置无路由匹配时,显示首页组件
const routes: Routes = [
{ path: '**', redirectTo: 'home' },
];
5,通过a
标签进行跳转(此时html文件)。[routerLink]
属性是用来动态设置跳转的路由,routerLinkActive
属性是用来设置路由被选中时的样式,需要在scss或者css
文件中声明active
类。
<header class="header">
<!-- 动态路由 -->
<a [routerLink]="[ '/home']" routerLinkActive="active">首页</a>
<!-- 静态路由 -->
<a routerLink= '/home' routerLinkActive="active">首页</a>
<a [routerLink]="[ '/news']" routerLinkActive="active">新闻</a>
<a [routerLink]="[ '/product']" routerLinkActive="active">商品</a>
</header>
<router-outlet></router-outlet>
以上便是关于angular路由跳转的全部分享,大家学会了吗,更多内容干货可关注慕课网~