Angular 2: Using a component in two diffrent ways:

2019-07-07 17:32发布

This is a general question concerning Angular 2 (no source code here)

In Angular2 components can be assigned as the target of a specific route of the router. The route

/something/:myId

might activate the "SomethingComponent".

Meanwhile components can be pulled into other components by referencing the selector in the template like this:

<something-component [myId]="'123'"></something-component>

Is it ok to use one component in both ways? Can I distinguish within the component, how it was activated?

1条回答
戒情不戒烟
2楼-- · 2019-07-07 18:14

You can inject the Router like

constructor(@Optional() private router:Router) {}

As far as I remember if it is not a routed component the router won't be injected.

You could also add an @Input() someName and use it like <some-dual [someName]="someValue">. Inputs aren't set when the component is added by the router.

You could also use a wrapper element that doesn't do anything but wrapping the component, and forwarding bindings so that they are set in <some-dual> the same way as when added by the router (for example by a shared service instead of bindings) and the wrapper could set an additional flag that indicates that the component was instantiated from a template instead of from the router.

查看更多
登录 后发表回答