可选路由参数
主要用于返回上一个组件使用,就是把当前组件路由参数添加到返回后的组件路由参数上。
使用步骤
- 基于单击事件触发路由
template: `
<h3>The department you picked is {{departmentId}}</h3>
<button (click)='goPre()'>previous</button>
<button (click)='goNext()'>next</button>
<button (click)='goBack()'>back</button>
`,
//注意第二参数就是可选路由参数
goBack(){
this.route.navigate(['/departments',{id:this.departmentId}])
}
- 在上一级组件中由已激活路由:ActiveRoute接收可选路由参数(使用paramMap Obeservable 订阅)
constructor(private router: Router, private aRouter: ActivatedRoute) { }
selectedId:number;
ngOnInit() {
this.aRouter.paramMap.subscribe((params:ParamMap)=>{
this.selectedId=parseInt(params.get('id'));
});
}
- 对模板中的列表标签使用类绑定,根据可选路由参数是否等于所展示的数据id给标签绑定select类,最后对select类设置激活样式。
//模板
<li (click)='onSelect(department)' [class.select]='isSelected(department)' *ngFor='let department of departments'>
<span class='badge'>{{department.id}}</span>{{department.name}}
</li>
//判断id
isSelected(departmentId){
return this.selectedId===departmentId.id;
}
//设置css样式