The componentComponent — a dynamic way of inserting components in Angular

TL:DR: Find the componentComponent on GitHub here: https://github.com/filipbech/component-component

With the introduction of Angular (2+), I was introduced to new concepts like static code analysis and all the glorious benefits of tree-shaking, AOT-compilation etc. I was amazed!

But then I realised, that meant a good bye to my AngularJS habbits of just creating a template string at runtime and then parsing it — to dynamically create content that is controlled by the server.

With Rc.4 (I believe) we got the magic sauce to dynamically create Components at runtime. I wrote a little wrapper component around that, the componentFactoryResolver. Even though it has been a while, I thought I would opensource it, if anybody else was searching for this.

You use the componentComponent by passing in a componentClass and a hash of the inputs it should have.

import { Component1, Component2 } from '...';
@Component({
template: `
<h1>This is dynamic...</h1>
<component [component]="cmp" [inputs]="inp"></component>
`
})
export class HasDynamicContentComponent {
public cmp;
public inp = {};

ngOnInit() {
this.cmp = someCondition ? Component1 : Component2;
this.inp['data'] = someData;
}
}

Be aware that if the components aren’t referenced from a template anywhere else, you need to add them to your ngModules entryComponents so they will not accidentally be shaken away from the bundle.

Or you can use its flexible api to repeat over a list of contents with different inputs:

import { GalleryComponent, TextComponent } from '...';
@Component({
template: `
<h1>Dynamic list</h1>
<component *ngFor="let block of contentBlocks" [component]="block.cmp" [inputs]="block.images"></component>
`
})
export class HasDynamicListOfContentComponent {
contentBlocks = [{
cmp: GalleryComponent,
data: {
images: /* list of images*/
}
},{
cmp: TextComponent,
data: {
text: 'hello world'
}
}];
}

You can find the componentComponent on GitHub right here: https://github.com/filipbech/component-component.

I hope this was helpful! PRs welcome.