Key takeaways:
The ng-content
directive enables content projection, allowing the creation of reusable components that can inject and display dynamic content in their templates.
ng-content
allows passing HTML elements or other Angular components from a parent to a child component, enabling highly customizable and reusable components.
ng-content
facilitates projecting varying content into a component while keeping the structure and behavior consistent.
In a dynamic button component, ng-content
can display different button labels based on parent input.
The ng-content
directive enables content projection that allows us to create reusable components to inject and display dynamic content in their templates. It is a placeholder to hold the dynamic content until it is parsed. Once the template is parsed, Angular replaces it with content.
In simpler terms, it lets us pass HTML elements or other Angular components from a parent to a child component. This process, known as content projection, gives us the ability to create highly customizable and reusable components. Without ng-content
, Angular components would have static content that can’t easily be changed or customized. But by using ng-content
, a parent component can pass dynamic content into a specific area of the child component’s template.
Why use ng-content
?
The primary reason for using ng-content
is to enable reusable components. In modern web applications, we often create components that are used in multiple places but need to display different content.
ng-content
allows us to:
Project dynamic content into reusable components.
Separate the structure of a component from its content.
Improve flexibility and customization of UI components.
For example, in a modal component, the structure (background, close button) remains the same, but the content (title, body, actions) may change depending on the context in which the modal is used.
How to use ng-content
in Angular
In Angular, ng-content
allows us to project content into a component. This is particularly useful when building reusable components where the content can vary, but the structure and behavior remain the same. Let’s explore a practical example by building a dynamic button component using ng-content
.
Example: Dynamic button with ng-content
This example demonstrates how to create a button that displays dynamic content based on what is passed into the component. Instead of hardcoding the button’s label, we will use ng-content
to allow content projection.
Step 1: Create the button component
Run the following command in the application directory to create a new component named button
that will use ng-content
.