【问题标题】:What should I use <ng-template> or *ngIf to display dynamic component?我应该使用 <ng-template> 或 *ngIf 来显示动态组件吗?
【发布时间】:2018-03-15 04:57:18
【问题描述】:

假设我有 2 个组件将有条件地显示。 我们可以通过两种方式做到这一点:

HTML

<div>
   <first-component *ngIf="shouldBeDisplayedFirst()"></first-component>
   <second-component *ngIf="shouldBeDisplayedSecond()"></second-component>
</div>

主要组件

shouldBeDisplayedFirst(){
   if(Something === true) {
      return true;
   }
}

shouldBeDisplayedSecond(){
   if(SomethingElse === true) {
      return true;
   }
}

它有效而且很短。

但我们也可以使用 &lt;ng-template&gt; 来做到这一点

HTML

<ng-template #myContainer><ng-template>

主要组件

@ViewChild('myContainer', { read: ViewContainerRef }) myContainer: ViewContainerRef;

constructor(private componentFactoryResolver: ComponentFactoryResolver) { }

ngOnInit() {
   loadCorrectComponent();
}

loadCorrectComponent() {
   let containerFactory = null;

   if (Something) {
      containerFactory = this.componentFactoryResolver.resolveComponentFactory(firstComponent);
   } else if (SomethingElse) {
      containerFactory = this.componentFactoryResolver.resolveComponentFactory(secondComponent);
   }

   this.myContainer.createComponent(containerFactory);
}
// and we have to declare these components to entryComponents in MainModule

如您所见,第一个解决方案更易于实施,但它是合适的解决方案吗?或者在这种情况下我应该以第二种方式来做?这些解决方案之间是否存在明显差异?

【问题讨论】:

  • 我喜欢这个问题。它显示了洞察力,我几乎怀疑你是出于其他原因而不是为了得到一个好的答案。

标签: angular architecture


【解决方案1】:

第一种方式代码更少,更易于阅读,更易于维护,在大多数情况下我都会推荐它。

我选择第二种方式的唯一原因是如果我有大量的条件组件。例如,我构建了一个表单构建器组件,它根据 JSON 描述构建表单,并且需要支持多种表单组件。在那里,动态实例化组件是有意义的。

【讨论】:

    【解决方案2】:

    如果您有两种解决方案可以解决同一个问题,我会选择一种更易于阅读、理解和维护的解决方案。

    此外,由于我们使用的是 Angular,因此应该尽可能避免操作或“了解”其模板的代码。这对于应用程序级别的组件比微级别的组件(按钮、列表等)更常见。

    如果您正在制作一个可重用的库,并且不知道模板中可能包含哪些组件,则可能需要后面的代码示例。一个很好的例子就是为什么 Angular 有两种创建表单的方式。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-08
      • 1970-01-01
      • 2017-12-03
      • 1970-01-01
      相关资源
      最近更新 更多