Angular 16 – 将组件输入与父路由的路由参数绑定

huangapple go评论64阅读模式
英文:

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'})

huangapple
  • 本文由 发表于 2023年6月12日 15:27:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/76454410.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定