In many cases we would change the content of a component dynamically, like for instance, to allow the user to change view or to let the children render the data retrieved and elaborated from its parent component. Here below we are going to show some techniques to create a component without deciding how the data would be shown. According with the application needs, each technique has its own strengths, but all of them encourage component reusability. We are going to describe:
- Content projection
- Dynamic templates
- Dynamic component creation
This is the simplest technique, and it allows the component user to decide what to show within the component. This could be useful, for example, if we want a container component to decide the main content structure without forcing what will be render in a certain section.
First of all, we need to use the
ng-content tag in the dynamic component.
Then, when we use the component, we could include all the content we want within the new component tag.
A more flexible way to use content projection can be achieved by using the class selector. In this case, the dynamic content specifies by using a class selector where the content will be injected.
Now, in the component user, we could include two elements that will be injected in the component.
Dynamic template is a very easy to use, but it comes with some problems in terms of flexibility, so it could be a good choice in case of simple mechanisms to be implemented. A typical example could be the rendering of two elements according with a condition.
It could be very useful also to avoid template part repetitions, by writing the html part once, and by using the template context to pass data to the template.
Dynamic Component creation
The dynamic component creation is by far the most flexible technique to use, because it allows to choose the instant on which the component will be created. On the counterpart, it is the most complicated to write, even if, after the first times, everything becomes more clear and easy to repeat.
To implement this technique we need:
a container tag directive, used to reference the container from within the parent component, to tag where the new child component will be rendered.
from the parent component, we need to reference the container using the
in the parent component, we use the
ComponentFactoryResolverto create an instance of the component to be created
As many other times in programming, there are different ways to accomplish the same task, but often it depends on what are the software requirements and what is the result we want to achieve. This article isn’t intended to be a detailed guide about these techniques, but only a general description about some of the possibilities offered by Angular to dynamically draw content within a component.