我应该使用<ng-template>或* ngIf来显示动态组件?

时间:2018-03-14 20:29:13

标签: angular architecture

假设我有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;
   }
}

它有效,而且很短。

但我们可以使用<ng-template>以及

来完成此操作

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

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

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

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

此外,由于我们使用的是Angular,因此应该避免使用操作的代码或者知道&#34;它的模板尽可能多。对于应用程序级组件而言,这通常比微级组件(按钮,列表等)更真实。

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

相关问题