【发布时间】: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;
}
}
它有效而且很短。
但我们也可以使用 <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
如您所见,第一个解决方案更易于实施,但它是合适的解决方案吗?或者在这种情况下我应该以第二种方式来做?这些解决方案之间是否存在明显差异?
【问题讨论】:
-
我喜欢这个问题。它显示了洞察力,我几乎怀疑你是出于其他原因而不是为了得到一个好的答案。
标签: angular architecture