angular - 在模块上的 2 个 Angular 组件之间进行选择

标签 angular

我有一些客户使用的 Angular 项目。因此,每次我为一个客户构建项目时,都会更改配置文件的属性。此外,对于不同的客户,我可能对某些组件的逻辑略有不同。例如:

@Component({
  selector: 'my-component',
  templateUrl: './component.template.html',
  styleUrl: './component.styles.scss'
})
export class MyBaseComponent {
  getName() {
    return 'Base';
  }

  /* Other logic here ... */
}

@Component({
  selector: 'my-component',
  templateUrl: './component.template.html',
  styleUrl: './component.styles.scss'
})
export class MyClientComponent extends MyBaseComponent {
  getName() {
    return 'Client';
  }
} 

@Component({
  selector: 'my-component',
  templateUrl: './component.template.html',
  styleUrl: './component.other-client.styles.scss'
})
export class MyOtherClientComponent extends MyBaseComponent {
  getName() {
    return 'Other Client';
  }
} 

现在,我希望它对导入该组件的其他模块完全透明。请注意,所有三个选择器的名称都相同。我尝试像这样实现模块:

import { client } from '../environment';
import { MyBaseComponent, MyClientComponent, MyOtherClientComponent } from './components';

function chooseComponent() {
  switch(client) {
    case 'my-client':
      return MyClientComponent;
    case 'my-other-client':
      return MyOtherClientComponent;
    default:
      return MyBaseComponent;
  }
}

@NgModule({
  declarations: [chooseComponent()],
  imports: [],
  providers: [],
  exports: [chooseComponent()],
})
export class TestComponentModule {}

但是 Angular 不允许我这样做。你们知道实现这个的正确方法是什么吗?当然,我可以使用 and if 来改变逻辑。但这很丑陋。

此外,如果我想根据客户端更改一段 html 模板。怎么做最好?想象一下,如果客户是 X,我会显示一个按钮,如果是 Y,我会显示标签。使用 ngIf 是唯一的方法吗?

谢谢!

最佳答案

有几种方法可以做到这一点。 1- 您可以创建一个容器组件并在模板中使用 ngSwitch。在这种情况下,您需要为每个组件使用一个唯一的选择器,并在容器组件模板中使用它:例如

容器模板

<ng-container [ngSwitch]="client">
  <my-client-component *ngSwitchCase="'my-client'"></my-client-component>
  <my-other-client-component *ngSwitchCase="'my-other-client'"></my-other-client-component>
</ng-container>

2- 您可以使用动态渲染并在您的容器组件 typescript 文件中施展魔法。您可以定义一个带有客户端变量开关的方法,并让 Angular 根据客户端在 View 中渲染组件。 有关如何呈现动态组件的更多详细信息,请参阅 angular dynamic component render documentation . 如果您不想将其他客户端组件加载到浏览器,您可以将您的组件放在惰性模块中并使用动态导入来导入它们。 看到这篇好文章 https://medium.com/@ckyidr9/lazy-load-feature-modules-without-routing-in-angular-9-ivy-220851cc7751

关于angular - 在模块上的 2 个 Angular 组件之间进行选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70190811/

相关文章:

javascript - Angular 5 : I can navigate to a module's route without including the module's path segment in the URL?

typescript - Angular 2 和 Visual Studio 2015 与 ReSharper 2016.1

android - 当应用程序从前台被杀死时在 Ionic App 中显示通知

javascript - webkit 掩码图像抛出一个 cors 错误 Angular

java - 为什么我的参数没有传递到 RESTful Web 服务?

javascript - Angular 中 mat-autocomplete 中的字符串替换

angular - 如何在 angular2/浏览器上使用 mongoose

javascript - Rxjs : prevent pushing data to subjects from outisde the service

angular - 如何将新字体导入项目 - Angular 5

java - Angular 2 应用程序部署在 JBOSS 6.4 eap 上,以 java 服务作为后端