Angular how to call dynamic components with dynamic modules

Viewed 326

I wanna call components dynamically, I have this code:

@NgModule({
  imports: [
    BrowserModule,
    MatButtonModule,
    NgxDatatableModule,
    MatToolbarModule,
    MatButtonModule,
  ],
  declarations: [
    DynamicComponent
  ],
})
class DynamicModule {}

const mod = this.compiler.compileModuleAndAllComponentsSync(DynamicModule);
const factory = mod.componentFactories.find((comp) =>
  comp.componentType === DynamicComponent
);

const componentRef = this.contentContainer.viewContainerRef.createComponent(factory);
(componentRef.instance as SkeletonComponent).data = tab.tabData;

And this is working fine.

In this component I get an import, which has a title, a tab data, and the iterating part, a component. What I'm trying to do is, that in the code above, I don't call DynamicComponent, but instead the tab.component.

Once I change the DynamicComponent in the declarations and in the factory, I have the following problems with that:

Error: Angular JIT compilation failed: '@angular/compiler' not loaded!

and

Value at position 0 in the NgModule.declarations of DynamicModule is not a reference: [object Object]

77       declarations: [
                       ~
78         tab.component
   ~~~~~~~~~~~~~~~~~~~~~
79       ],

EDIT

tab is an Input, of type Tab

import {Type} from '@angular/core';

export class Tab {
  public id: number;
  public title: string;
  public tabData: any;
  public active: boolean;
  public component: Type<any>;

  constructor(component: Type<any>, title: string, tabData: any) {
    this.tabData = tabData;
    this.component = component;
    this.title = title;
  }
}
0 Answers
Related