angular - 获取相对于父路由的 url 段
问题描述
在具有嵌套路由配置的 Angular 11 应用程序中,我想知道 url 相对于父路由是什么。
例如,如果我的路线配置是
{
'car/:id', children: [{ path: 'tyres', CarTyreComponent }],
}
并且用户在car/5/tyres,答案是"tyres"
。
此外,我希望能够更新和访问模板中的值,以便像这样突出显示轮胎部分:
[ngClass]="if this.router.url.startsWith('tyres') ? 'active' : ''"
但是上面的示例在嵌套时不再有效,而且我似乎陷入了 and 的可订阅和不可订阅ActivatedRoute
选项Router
。
什么有效,但似乎是一种容易出错的方法,是这样的:
[ngClass]="this.router.url.split('/')[3] === 'tyres' ? 'active' : ''"
还有更好的方法吗?
解决方案
如果您尝试从子组件中获取 url 段,则它应该是:
在您的component.ts
:
urlToCheck$$: Subject<string> = new Subject();
constructor(private _route: ActivatedRoute){
this._route.parent?.url.subscribe( url => this.urlToCheck$$.next(url[0].path) )`
在 html 中:
[ngClass]="(urlToCheck$$ | async) === 'tyres' ? 'active' : ''"
推荐阅读
- javascript - 使用循环查找下一个回文
- flutter - 如何在颤振中重用有状态的小部件
- c# - 带有 dotnet Core 3.1 用户标识的令牌和 JWT,localStorage.getItem("token") 为 null
- python - 在带有附加条件的熊猫中删除“重复行”
- android - 向右滑动打开另一个活动
- spring-boot - 如何分配 id 映射实体
- raspberry-pi - 端口转发 Raspberry Pi 的共享 Internet 连接
- flutter - 提供者:为每个页面序列创建新的模型对象
- ios - Swift - 设置变量属性并发或多线程安全吗?
- python - Airflow - 在 DockerOperator 中使用 run_id 作为卷名