【问题标题】:How do I conditionally compile environment-specific template in Angular如何在 Angular 中有条件地编译特定于环境的模板
【发布时间】:2018-05-18 07:20:40
【问题描述】:

我的 Angular 5 应用程序具有多种环境(dev、qa、customer1、customer2 等)。使用environment.xxx.ts 我可以毫无问题地获得运行时配置变量。但是,我不能在编译期间有条件地包含模板。也就是说,我想要这样的东西:

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

其中environment.clientenvironment.customer1.ts 提供。

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

注意 1:我意识到很快我们将获得允许结合 AOT 和 JIT 编译器的 Ivy 渲染器;但我并没有尝试动态加载模板 - 仅根据环境编译正确的模板。

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

【问题讨论】:

    标签: angular angular-cli


    【解决方案1】:

    我知道你发布这个问题已经有一段时间了,但我们遇到了同样的问题,我只是通过使用不同的模块解决了这个问题。

    我有一个模块 (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 {}
    

    所有客户特定的组件都捆绑在一个客户模块中。在这个例子中,客户模块可能只声明和导出导航组件。默认模块声明和导出相同的组件。重要的是,每个组件中的选择器都是相同的。这意味着,在两个模块中:customer-module 和 default-module,导航组件具有相同的选择器(app-navigation)。

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

    【讨论】:

      猜你喜欢
      • 2011-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-05
      • 1970-01-01
      相关资源
      最近更新 更多