angular2中动态创建Component

当使用Angular2,并且与第三方库打交道时,有时需要使用JS代码(TS代码)动态创建一个Component,然后把这个Component的原生dom对象传入到第三方库的API中去。这如何做到呢?简单来说分为4步:

  1. 使用 ComponentFactoryResolver 和目标Component类对象,创建一个ComponentFactory;
  2. 使用 ViewContainerRef 的 createComponent方法,传入刚刚得到的ComponentFactory对象,实例化一个Component;
  3. 给Component的instance中的 @Input 属性赋值。
  4. 引用 Component.location.nativeElement,丢给第三方库的API。

参考 Angular2中动态注入Component