4

I have Angular 5 application with several environments (dev, qa, customer1, customer2, etc.). Using environment.xxx.ts I get runtime configuration variables with no problem. However, I can't conditionally include a template during compilation. That is, I would like to have something like that:

@Component({
    selector: 'app-hello',
    templateUrl: `hello.component.${environment.client}.html`
})

where environment.client is provided by environment.customer1.ts.

Maybe it's a bigger question - how can I control template or stylesheet in Component's metadata.

NOTE 1: I realize that soon we will get Ivy renderer that will allow to combine AOT and JIT compilers; but I am not trying to load the template dynamically - only compile the right template depending on the environment.

NOTE 2: I tried dotenv, but it seems to work the same way: it gives me control of the environment variables at runtime, but doesn't help to choose the right file for compilation.

Felix
  • 9,248
  • 10
  • 57
  • 89

1 Answers1

0

I know its been a while since you posted this question, but we have the same issue and I just resolved it by using different modules.

I have a module (customer-components.module.ts) which decides which customer components are included depending on the enviornment.

const customerComponents = [CustomerModule];
const defaultComponents = [DefaultModule];

// I just realised functions are not working in aot
// not the best way if there are lots of customers which is the case for us. 
// i will see if i can find a nicer way to decide on the components. but the mechanisim works

const exports = env.customer === 'customer1' ? customerComponents : defaultComponents; 

 @NgModule({
  imports: [
    CustomerModule,
    DefaultModule,
    CommonModule
  ],
  declarations: [],
  exports: getExports()
})
export class CustomerComponentsModule {}

All customer specific components are bundled within one customer-module. In this example customer-module may only declares and exports the navigation.component. The default-module declares and exports the same components. Important is the fact, that the selectors in each component are identical. This means, in both modules: customer-module and default-module, there the navigation-component have the same selector (app-navigation).

Now I can import the customer-module whereever I want, e.g. in the app-module. and use in the app.component.html and the environment directs which navigation component is being exported and used within the app.component.

Erbsenkoenig
  • 1,584
  • 14
  • 18