JustDoItTomorrow
3/11/2018 - 1:22 AM

ViewContainerRef

// 这里是通过createEmbeddedView来创建,其中templateRef是TemplateRef

if (!condition) {
  this.viewContainer.createEmbeddedView(this.templateRef);
} else {
  this.viewContainer.clear();
}
// 这里是通过ViewContainerRef的createComonent方法来创建

// 创建factory
let componentFactory = this.componentFactoryResolver.resolveComponentFactory(adItem.component);

// 通过directive(adHost)来获取ViewContainerRef,这里是一个<ng-template></ng-template>
let viewContainerRef = this.adHost.viewContainerRef;
viewContainerRef.clear();

// 调用其createComponent来创建
let componentRef = viewContainerRef.createComponent(componentFactory);

// 设置其@Input()参数
(<AdComponent>componentRef.instance).data = adItem.data;

// NOTE:
// 通常,Angular编译器会为模板中所引用的每个组件都生成一个ComponentFactory类。 但是,对于动态加载的组件,模板中不会出现对它们的选择器的引用。
// 要想确保编译器照常生成工厂类,就要把这些动态加载的组件添加到NgModule的entryComponents数组中:
// entryComponents: [ HeroJobAdComponent, HeroProfileComponent ],