Angular路由

路由就是根据不同的url地址,动态的让根组件挂载其他组件来实现一个单页面应用。
安装路由

ng generate module app-routing --flat --module=app

路由安装后的变化

  • 增加了app-routing.module.ts (配置路由的模块)
  • 在app.module.ts中引入了AppRoutingModule的模块(注入)
  • 在app.component.html中有< router-outlet >< / router-outlet >

步骤

  • 1.创建项目
  • 2.创建需要的组件(ng g c components/news)
  • 3.找到app-routing.module.ts配置路由
    引入组件

//将新建的组件引入
import { NewsComponent } from './component/news/news.component';
import { HomeComponent } from './component/home/home.component';
import { ProdComponent } from './component/prod/prod.component';

import { NewscontentComponent } from './component/newscontent/newscontent.component';
	配置路由
const routes:Routes=[
  {
    path:'home',component:HomeComponent
  },
  {
    path:'news',component:NewsComponent
  },
 {
    path:'newscontent',component:NewscontentComponent
  },
  {
    path:'prod',component:ProdComponent
  }
];

  • 4.找到app.component.html根组件模块,配置router-outlet显示动态加载的路由
<h1>我是根组件</h1>

<header>
  <a [routerLink]="['/home']">首页</a>
  <a routerLink='/news'>新闻</a>
  <a [routerLink]="[ '/prod']">产品</a>
</header>

<router-outlet></router-outlet>
  • 5.设置默认组件
 {
    path:'**',
    redirectTo:'home'//任意的路由,匹配不到路由的时候加载的组件,或者跳转的路由
  
  }
  • 6.活跃时的组件(跳转是的默认样式)
 <a [routerLink]="[ '/home' ]" routerLinkActive="active">home</a>
  <a [routerLink]="[ '/news' ]" routerLinkActive="active">news</a>
  <a [routerLink]="[ '/prod' ]" routerLinkActive="prod">home</a>


.active{
	color:red
}

路由跳转传值

新闻跳转到新闻详情
创建新闻详情组件 newcontentComponent

在news.component.html中

<a [routerLink]="[ '/newscontent' ]">跳转新闻详情</a>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值