如何在Angular

时间:2018-05-18 07:20:41

标签: angular angular-cli

我有几个环境的Angular 5应用程序(dev,qa,customer1,customer2等)。使用environment.xxx.ts我得到运行时配置变量没有问题。但是,我无法在编译期间有条件地包含模板。也就是说,我希望有类似的东西:

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

environment.clientenvironment.customer1.ts提供。

也许这是一个更大的问题 - 如何在Component的元数据中控制模板或样式表。

注1 :我意识到很快我们将获得Ivy渲染器,它将允许组合AOT和JIT编译器;但我不是试图动态加载模板 - 只根据环境编译正确的模板。

注意2 :我尝试了dotenv,但它的工作方式似乎相同:它让我可以在运行时控制环境变量 ,但不是帮助选择正确的文件进行编译。

1 个答案:

答案 0 :(得分:0)

自您发布此问题以来,我知道已经有一段时间了,但是我们有相同的问题,我只是通过使用不同的模块来解决了。

我有一个模块(customer-components.module.ts),它可以根据环境决定要包括哪些客户组件。

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 {}

所有特定于客户的组件都捆绑在一个客户模块中。在此示例中,客户模块只能声明并导出navigation.component。默认模块声明并导出相同的组件。重要的事实是,每个组件中的选择器都是相同的。这意味着,在两个模块(客户模块和默认模块)中,导航组件具有相同的选择器(应用程序导航)。

现在,我可以在任何需要的地方导入客户模块,例如在应用程序模块中。并在app.component.html中使用,环境指示在app.component中导出和使用的导航组件。