In the previous post of “You don’t Know Angular” series, we have discussed how we project data into a component. We have learned projections at specific places inside the component using the projection slots concept.

In this post, we are going to learn “ How and Why of Dynamic Components”

We will learn:

How to create a dynamic component?

How to attach @Input to a Dynamic Component?

Let’s understand these concepts using a Pizza Creator Application.

Problem Statement

Suppose, you own a pizza shop, where anybody can order a customized pizza. The customization of the pizza is dependent on the customer and will be displayed at the end. You need to design a software that displays a pizza along with its customization at the end of each order.

Pizza and the toppings 😄

Approach

Now, we understood the problem, as each of the pizza is different, we can not define a set template for the pizza content. We will generate the pizza dynamically to place the order.

Generating Pizza dynamically? 😕 Yes, the customer will select the toppings and we will make the delicious pizza component dynamically based on the selection.

Angular provides us the Dynamic Component Loader which makes this very easy for us to create these components. In Angular, we can use the componentFactoryResolver to resolve the factory which is a requirement to create any component.

Our first task, is to create two components

Choices Component — To help the customers, to choose the toppings on the Pizza.

— To help the customers, to choose the toppings on the Pizza. Pizza Component — To create the pizza dynamically

Note: The choices component will use the Pizza Component to create a pizza dynamically.

Creating the Choices Component

The choices component will have the following parts:

Toppings Array containing all choices

SelectTopping Method for choosing the toppings

DOM node to Inject the Dynamically Created Component

CreatePizza Method to create the Pizza Component dynamically

Let’s begin by creating and initializing the toppings Array. We have placed all our images inside the assets/ and the name of these images are the same as the name of the elements inside the toppings array.

Toppings Array

Now, we will loop this array to display our choices on the page.

Looping Toppings Array

Now, our page contains the toppings panel to click and select any of the toppings for the pizzas which looks like below: