Angular 2/4 component with dynamic template or templateUrl

Viewed 15932

I have been trying to find a solution for this everywhere.

I have a project with different 'skins', which are basically different sets of templates/Css.

I am trying to have my components use the skin based on a variable THEME_DIR.

Unfortunately, I cannot find how to make that happens. I looked into the Dynamic Component Loader on angular.io without success.

I also looked at a few answers here without success either.

Does anyone have an idea?

This is what I tried so far:

import { ComponentFactoryResolver, ViewContainerRef } from '@angular/core';

// @Component({
//     templateUrl: '../../assets/theme/'+THEME_DIR+'/login.template.html',
// })

export class LoginComponent implements, AfterViewInit {


    private log = Log.create('LoginPage');

    constructor(private mzksLsRequestService: MzkLsRequestService,
                private componentFactoryResolver: ComponentFactoryResolver,
                public viewContainerRef: ViewContainerRef) {
    }



    ngAfterViewInit() {
        let componentFactory = this.componentFactoryResolver.resolveComponentFactory(new Component({
            templateUrl: '../../assets/theme/default/login.template.html',
        }));
        let viewContainerRef = this.viewContainerRef;
        viewContainerRef.clear();
        let componentRef = viewContainerRef.createComponent(componentFactory);

    }

}
3 Answers

As of Ivy (I think) we can use static variables (for example enviroment) in templateUrl. for example:

    import { environment } from 'src/environments/environment';
    @Component({
        selector: 'home',
        templateUrl: `./skins/${environment.skin}/home.page.html`,
        styleUrls: ['./skins/${environment.skin}/home.page.scss']
    })
Related