Tip #7 [Conditional rendering]
Often you need to change visibility of some parts of your Angular application. When it comes to end-user, there’s no difference whether you hide an element with the aid of CSS or remove it from the DOM. However, as a developer, you need to take into account whether component instantiation is eager or lazy for a given scenario. In addition, some solutions, in particular CSS-based, only hide content on the user interface, while components still occupy memory and are present in components tree.
Let’s consider an exemplary component that you want to render conditionally:
NgIf for component
- the component is not created until showBanner is set to true,
- the component is created/destroyed for each toggle action.
NgIf for content projection slot
usage:
- the component is created eagerly independent of showContent value,
- the component is created once only.
Content projection slot hidden with CSS
usage:
- the component is created eagerly independent of showContent value,
- the component is created once only.
Passing TemplateRef
usage:
- the component is not created until showContent is set to true,
- the component is created/destroyed for each toggle action.
TemplateRef with content projection slot
usage:
- the component is created eagerly independent of showContent value,
- the component is created once only.
Live example:
If you like the tip, please give me some applause 👏