- read

Dynamic Components in Angular

Heloise Bahadiroglu 68

Dynamic Components in Angular

Heloise Bahadiroglu
JavaScript in Plain English
4 min read3 days ago

--

Dynamic components in Angular allow you to load components at runtime for cases in which you don’t know at build time which component will have to be rendered.

For example, in a normal list / item case, you would have a ListComponent, in which you would render an ItemComponent for each item in your list using an *ngFor directive. That works if you know how each item in the list should be rendered.

Let’s take a dumb but concrete example. You have a list of pets. Some are dogs, some are cats. Cats and dogs have different attributes and should be rendered differently, and you of course don’t know in advance how the list of pets returned by the server will look like. One solution for this problem is to use dynamic components.

I had already written an article about it with Angular 8. The process has been simplified since then, let’s update the example.

If you have cats and dogs implementing a common interface Pet:

export default interface Pet {
name: string;
age: number;
profilePicture?: string;
}
import Pet from './Pet';

export default interface Dog extends Pet {
favoritePark: string;
}
import Pet from './Pet';

export default interface Cat extends Pet {
favoriteComfyPlace: string;
}

you might want to render cats with their favorite comfy place:

<div class="card">
<img [src]="member.profilePicture || 'assets/cat.png'"/>
<div class="info">
<div class="name">{{member.name}}</div>
<div class="age">Age: {{member.age}}</div>
<div class="favorite-comfy-place">Favorite Comfy Place: {{member.favoriteComfyPlace}}</div>
</div>
</div>

while we want to render dogs with their favorite park:

<div class="card">
<img [src]="member.profilePicture || 'assets/dog.png'" />
<div class="info">
<div class="name">{{member.name}}</div>
<div class="age">Age: {{member.age}}</div>
<div class="favorite-park">Favorite Park: {{member.favoritePark}}</div>
</div>
</div>

to end up with a list of members looking like this: