Jack Sun
Jack Sun

Reputation: 2132

In Angular, how can one component to have multiple HTML templates?

I am developing an ecommerce application, and one major feature is that this app should have multiple themes. The total number of themes could be 100 or even more. However, these themes all have the same data (For example: all home page have same banner images, new product, feature product data.) .

I know I can use ng-template or TemplateRef to determine which piece of HTML should display. But since I have over 100 themes, both ng-template or TemplateRef methods will load a lot of extra files. So I think I need some sort of lazy load, when a component loads the data then lazy loads the correct HTML template. So how can I have this work?

Idea structure

Upvotes: 3

Views: 1177

Answers (3)

Aviad P.
Aviad P.

Reputation: 32629

Looks like it is possible, all our routes are handled by lazy loaded modules. This is our out-of-the-box route config:

const routes: Routes = [
  { path: '', loadChildren: () => import('./lazy/lazy.module').then(m => m.LazyModule) }
];

While module lazy has this route config:

const routes: Routes = [
  { path: 'home', component: HomeComponent },
]

While HomeComponent is taken from the declarations of module lazy.

Then define another module, called for example lazy-two with the same route config, and its own HomeComponent.

Finally, you can switch between the modules by using this code:

lazyLoad() {
  const routes: Routes = [
    { 
      path: '', 
      loadChildren: () => import('./lazy-two/lazy-two.module')
                            .then(m => m.LazyTwoModule)
    }
  ];

  this.router.resetConfig(routes);
  this.router.navigateByUrl('/home');
}

This will lazy load module lazy-two and refresh the route to /home - you will see the component of the new module displayed.

I couldn't create a stackblitz, some errors occurred probably because of lazy loading. So I ran it locally on my machine and pushed the code to GitHub

EDIT I managed to make a StackBlitz

Upvotes: 1

gaspar aufranc
gaspar aufranc

Reputation: 1

what about using the same component and styling it different when you select the template?

Upvotes: 0

Andres Doncel
Andres Doncel

Reputation: 44

I recommend used ComponentFactoryResolver to create the components that you need to render.

this.templates = [
  {
    id: "template-1",
    component: Template1,
  },
  {
    id: "template-2",
    component: Template2,
  },
];

  ngOnInit() {
    this.templates.forEach((element) => {
      this.containerReference.createComponent(
        this.factoryResolver.resolveComponentFactory(element.component)
      );
    });
  }

in the .html you should have

<ng-container #containerReference><ng-container>

Upvotes: 0

Related Questions