Switch template html,scss dynamically in angular

Viewed 293

I have header component like in the following format:

app-header (folder)
     classic (folder)
         app-header.component.html
         app-header.component.scss

    elegant (folder)
         app-header.component.html
         app-header.component.scss

    simple (folder)
         app-header.component.html
         app-header.component.scss

 app-header.component.ts

I want to switch between these template folders(classic,elegant,simple) dynamically. I mean, get template folder name from db through an http-request and load html and style from that folder respectively.

I have done it by set folder name in an environment variable and load according to that. How could i set that environment variable by calling an API and load html and styles according to that?

following is the code i tried to load from environment variable in app-header-component.ts

import { Component, OnInit } from '@angular/core';
import { ConfigService } from './../config.service';
import { environment } from './../../environments/environment';

let theme_name  = environment.theme_name;

const header      = require('./' + theme_name + '/app- 
header.component.html');

const style     = [require('./' + theme_name + '/app- 
header.component.scss')];

@Component({
    selector: 'app-header',
    template: header,
    styles: style
})
2 Answers

The parent component could keep track of the theme and letting it to decide which header component to render.

<app-header-classic *ngIf="theme === 'classic'"></app-header-classic>
<app-header-elegant *ngIf="theme === 'elegant'"></app-header-elegant>
<app-header-simple *ngIf="theme === 'simple'"></app-header-simple>

Have you tried something like this?

@Component({
  selector: 'selector',
  templateUrl: environment.template_path,
  styleUrls: [environment.style_path]
})
Related