Amir Popovich
Amir Popovich

Reputation: 29836

Compiling & rendering existing components dynamically with Angular 5

I have an angular 1.x app which works with a dynamic layout. The app receives a layout json with the screen's metadata and simply, generates compiled components on the fly and creates a screen.

The relevant "important code" looks like this:

const element = this.$compile(`<${this.control.type} control="control" data="data"></${this.control.type}>`)(scope);
this.$element.replaceWith(element);

Now, I'm trying to migrate this to Angular 5 and I've understood that Angular 5 dropped the DOM manipulation and the $compile functionality.

I've searched all around and found solutions that know how to render dynamic html (e.g. {{1+1}}) and other deprecated stuff (prior to Angular 5), but couldn't find a fit for rendering dynamic made components (and handling their inner bindings).

Is there any way I can accomplish this kind of functionality

Upvotes: 0

Views: 575

Answers (1)

G.Vitelli
G.Vitelli

Reputation: 1287

This is the way to create a component by your self like angularJS: (Don't forget to destroy it! call destroy() on the componentRef to do this)

Parent Component:

@ViewChild('componentHolder', { read: ViewContainerRef }) componentHolder: ViewContainerRef;

constructor(private componentFactoryResolver: ComponentFactoryResolver) { }
public createComponent(): void {
          const componentFactory = this.componentFactoryResolver.resolveComponentFactory(MyComponent);
          const componentRef = this.componentHolder.createComponent(componentFactory);
}

Parent Component HTML:

<button (click)="createComponent()">Add New MyComponent below</button>
<div #componentHolder ></div>

Add the MyComponent in the NgModule:

...
  imports: [
    BrowserModule,
    FormsModule,
    RouterModule.forRoot(appRoutes),
  ],
  entryComponents: [
    MyComponent
  ],...

Upvotes: 1

Related Questions