问题
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