继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

angular路由跳转,代码自取

幕布斯7119047
关注TA
已关注
手记 432
粉丝 28
获赞 99

    今天来个大家分享angular路由跳转的方法,话不多说直接上代码:

a标签进行跳转:

    1,创建组件ng g c homeng g c newsng 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路由跳转的全部分享,大家学会了吗,更多内容干货可关注慕课网~


打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP