The componentComponent — a dynamic way of inserting components in Angular

Filip Bech-Larsen
Oct 25, 2017 · 2 min read

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.

IMPACT Developers

Digital agency with 190 employees and offices in Aarhus…

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store