DEV Community

Discussion on: Dynamic Layout parts in Angular

Collapse
 
anduser96 profile image
Andrei Gatej

Hi!

I’d follow this approach:

  • create a custom injection token: DYNAMIC_HEADER_INJECTOR
  • register the components that should be inside the ‘header tag’ in a module(AppModule) under the above token
  • create a directive that will deal with rendering logic
<header>
  <ng-container yourDirective><ng-container>
<header>

Then, in your directive, you’d inject the ActivatedRoute and the ViewContainerRef and based on your logic, you’d render one component from the array(meaning that you’d also inject DYNAMIC_HEADER_INJECTOR).

Collapse
 
negue profile image
negue

Hi :)

First.... Congratulations, you are the first comment of my posts 🎉

Back to topic:

I haven't thought about doing this with injection tokens, lets play it out:

  • I'd create the DYNAMIC_HEADER_INJECTOR and provide it with
{
      provide: DYNAMIC_HEADER_INJECTOR,
      useValue: {
        components: [
          {
            path: '/some-sub-page',
            component: MyComponent
          },
          {
            path: '/some-other-page',
            component: MySuperSelectionComponent
          }
        ]
      }
    }
  • and the directive would create those components if the specific route was navigated to..

but wouldn't it be then like in the 1st solution ?

The components would have to be registered and imported to the AppModule which ends-up raising the initial load of your app

Thats why I wanted to have it loaded only where it really needed to be (and not in the AppModule in my case)

or did I misunderstood your idea?

Collapse
 
anduser96 profile image
Andrei Gatej

No, you’re right.

I think there is a way to mitigate this issue, but this implies more work from the developer.

If we don’t want to include the component in the main bundle, we can put it in its module and in the directive, based on some conditions, you can load the module on demand by using import(path/to/module).then() and injecting the compiler.

Thread Thread
 
negue profile image
negue

Yeah like you wrote, another way would be to lazy-load the components of it, there are some helper libaries for this.

I also have one 😁

Its better to have many possible ways to solve those issues, instead of none

Thread Thread
 
anduser96 profile image
Andrei Gatej • Edited

Thanks for sharing!

I’m skeptical about libraries, but I do like to explore them!