Context
I want to create a map component, which I want to reuse on various URLs. Instantiating this component is a bit time consuming, and also uses up tile requests to display the map images everytime the component is created.
Question
How can I reuse the same component instance on different urls when the component is nested in the tree?
On the stackblitz below, a new ReusableComponent
is instantiated every time I switch route
https://stackblitz.com/edit/angular-sr9stk?file=app%2Freusable.component.ts
Note
I know about RouteReuseStrategy
, but this only works for top level components (i.e. the defined in routing setup)
Using angular 5.2
A traditional way to reuse components is to place multiple components in a single repo and publish it as one package. This method is useful for saving the overhead of having to maintain components in many different repositories.
In this short post, we’ll list a few common ways to reuse components between different React projects and across different teams. I hope this will help in building your next app, alone or with your team. Enjoy. 1. Bit + Bit.dev Bit is a tool built for sharing components across projects and teams.
Bit and Bit.dev can be used to reuse components directly between apps, or to share many single-package components from a single library. Go to Bit.dev and create a collection. 2. Install Bit globally on your machine. 3. Clone the demo app. 4. Initialize a Bit workspace. 5. Add components to be tracked. 6.
And your reusable header component should be rendered to the page: Now adding a header to the page is as easy as adding a <script> tag pointing to components/header.js, and adding <header-component></header-component> wherever you want.
Kind of a hack but this was the only way I got it working
https://stackblitz.com/edit/angular-13dj9k
Creating the Component in a service as a ComponentRef then inserting it into a directive's ViewContatiner, the directive exists on each route. The hacky part was I had to listen the NavigationStart event to detach the component before the navigation so it could be reattached on the next route.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With