1.新建带路由配置的项目
ng new router –routing 会自动生成app-routing.module.ts文件
相关对象介绍:
简单解释:
Routes用法:path:‘user’,component:XXXComponent 指定显示的组件 注意(path不能用/XX,出现路径问题)
RouterOutlet:插座 使子组件在父模板中指定位置显示(html)
RouterLink:在父模板中通过a标签指向其他组件(html)
Router:组件中调用navigate()方法改变导航栏中的地址(component)
ActivatedRoute:保存传递路由时的参数信息和地址
需求:点击按钮1页面显示内容 ‘按钮1text’点击按钮2页面显示 ‘按钮2text’
1.新建组件showOne和showTwo
2.在html中设置不同的text以便区分
3.在app-routing.module文件中设置路径
const routes: Routes = [
//默认 path:'**'时为缺省路由
{path:'',component:ShowOneComponent},
{path:'test',component:ShowTwoComponent}
];
4.app.component.html文件
//默认路径 当前路径为根路径 若为./表示为子路径 (在child子路径中会用到)routerLink可以传递路径和参数
<a [routerLink]="['/']"></a>
<a [routerLink]="['/test']"></a>
<router-outlet></router-outlet>
5.通过Router的negative方法跳转同样可以实现此功能
在app.component.html文件添加个button
<button (click)="showText()">button</button>
6.app.component.ts
constructor(private router:Router){}
showText(){
console.log("rrrrr");
this.router.navigate(['/test']);
}