Posted under Angular & Knowledge Base & Routing & Web
Permalink
Tags Tutorial, Web
One of my goals is to be able to dynamically create routes based on configuration data, typically loaded at pre-init time using an app initialiser.
Two approaches I have seen to doing this are as follows:
- Using a custom Injector to use code to inject the routes.
This is done in this example here. The code for it is available here. - Using Router.resetConfig() to change the routes after initially creating them.
This is done in this example here. The code for it is available here.
It is also done in this example here, in the app initialiser.
Both are dynamic, but method 1/ with the injector runs before any app initialiser, so would not be suitable for my needs (I verified this with a simple test with console logging). If this were used, any dynamic config would need to be fetched within the injector code or called directly from it. Method 2/ can be used after the app initialiser – I tried calling it successfully from the ngOnInit lifecycle hook in the app component which worked fine.
This example here uses method 1/, and the code for it is on github here. I downloaded the code and modified the original version, as it contains errors in the time of day checking code. I then saved the project to bitbucket. I branched it and modified it again to use resetConfig as above from ngOnInit, and removed the injector mechanism. This also worked fine.
Whilst these approaches allow dynamic creation of the routes, they assume that the routed components are known to the application or declared in it in some form. The basis of the standard approach to routing is that the component class referred to in the route is looked up, and its selector is extracted and used to create the component tag dynamically, inserting it after the appropriate <router-outlet>. This would not work in the case of angular elements, i.e. W3C web components. These are entirely dynamic and my examples which use these in the past have the element name/component tag defined dynamically as part of the config, along with the names of the scripts to be loaded to create the web component. Another approach will need to be investigated to look into routing of angular elements.
Comments Off on Angular Dynamic Routing