Angular 2: Using a component in two diffrent ways: as target of a route and by selector <selector-my-component>

大城市里の小女人 提交于 2019-12-24 00:57:43

问题


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:


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.



来源:https://stackoverflow.com/questions/37944938/angular-2-using-a-component-in-two-diffrent-ways-as-target-of-a-route-and-by-s

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!