英文:
Angular 16 - Bind component input to route param from parent route
问题
想象一下在 Angular 16 中有一个组件(some.component.ts
),它从父路由的activeRoute
中获取其foo
属性的值。参见下面的示例:
@Input() foo!: string;
constructor(private activeRoute: ActivatedRoute) {
this.foo = this.activeRoute.parent?.snapshot.params['foo'];
}
我想在这里使用 Angular 16 的输入绑定到路由参数。对于其他情况,它可以正常工作,但我不确定在参数实际来自父路由时如何使其正常工作。
路由看起来是这样的:
{
path: 'bar/:foo',
component: IrrelevantComponent,
children: [
{
path: 'some',
component: SomeComponent,
},
],
},
是否有可能使用新的路由参数绑定来实现这一点?如果可以,那么如何做到?
英文:
Imagine a component (some.component.ts
) in Angular 16 which takes value for its foo
property from activeRoute
- but from the parent route. See the example below:
@Input() foo!: string;
constructor(private activeRoute: ActivatedRoute) {
this.foo = this.activeRoute.parent?.snapshot.params['foo'];
}
I would like to use the Angular 16 input binding to route params here. It works for other cases but I am not sure how to make it working when the param actually comes from a parent route.
The routes look like this:
{
path: 'bar/:foo',
component: IrrelevantComponent,
children: [
{
path: 'some',
component: SomeComponent,
},
],
},
Is this even possible to achieve using the new route param binding? If so then how?
答案1
得分: 2
@skink的评论链接到了如何执行此操作的文档:https://angular.io/guide/router#getting-route-information
如果您想要使用父组件的路由信息,您需要设置路由参数继承策略选项:withRouterConfig({paramsInheritanceStrategy: 'always'})
英文:
@skink's comment links to the docs which how to do this: https://angular.io/guide/router#getting-route-information
> If you want to use the parent components route info you will need to set the router paramsInheritanceStrategy option: withRouterConfig({paramsInheritanceStrategy: 'always'})
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论