Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reuse the same component instance on different urls

Tags:

angular

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

like image 379
David Avatar asked Apr 10 '18 15:04

David


People also ask

How do I reuse components in a project?

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.

How to reuse React components between different projects and teams?

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.

How do I reuse components between apps?

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.

How to add a reusable header component to the page?

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.


1 Answers

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.

like image 166
William Lohan Avatar answered Oct 19 '22 11:10

William Lohan