Dynamic Components in Angular

Heloise Bahadiroglu
codeburst
Published in
5 min readMar 30, 2020

Angular views are made of components that you can combine together to create more complex ones. But you might sometimes not know at build time which component should be displayed, and have to chose the right component at runtime. This is when dynamic components come in handy.

In this article, we are going to see through an example how to create and use them. We will develop a chat for pets in which we will need to display a list of connected members. At first, we will only allow dogs in the chat so we won’t need anything more than the classic Angular components. We will then allow cats to register. Cats have different fields, and we will need another component to represent them in the list. Our list of members will contain cats and dogs, and we will need to decide at runtime, depending on the specie of the member, which component has to be displayed, whether dog item component or cat item component.

Simple list of dog members

We have an array of dogs and we want to display them in a list.

List of members, only dogs

We define a dog interface, with a name, an age, a favorite park and optionally a profile picture.

In a real application, members would be retrieved from a server, but let’s mock them: we define a list of members in a members service.

We then need a list component that gets the members from the service and displays them.

We use a dog item component that looks like this:

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Published in codeburst

Bursts of code to power through your day. Web Development articles, tutorials, and news.

Written by Heloise Bahadiroglu

Freelance Software Engineer. I write about web and cloud technologies. AWS and Azure certified.

Responses (3)

Write a response