Member-only story
Dynamic Components in Angular
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.

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: