ng-content is a directive used in Angular for content projection, which allows developers to insert external content into a component’s template. This enables the creation of reusable and flexible components where the content can be defined by the parent component, rather than hardcoded in the child component. By using ng-content, you can build dynamic components that can display different content in various contexts, improving reusability and separation of concerns.
What is ng-content in Angular?
Key takeaways:
The
ng-contentdirective enables content projection, allowing the creation of reusable components that can inject and display dynamic content in their templates.
ng-contentallows passing HTML elements or other Angular components from a parent to a child component, enabling highly customizable and reusable components.
ng-contentfacilitates projecting varying content into a component while keeping the structure and behavior consistent.In a dynamic button component,
ng-contentcan 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.
ng generate component button
Step 2: Define the button component
In the ButtonComponent, we’ll define our dynamic button using ng-content. Here is the updated button.component.ts:
import { Component } from '@angular/core';@Component({selector: 'btn',templateUrl: './button.component.html',styleUrls: ['./button.component.css']})export class ButtonComponent {do() {console.log("Button clicked!");}}
Step 3: Define the HTML template for the button component
We’ll use ng-content to allow dynamic content projection inside the button:
<button (click)="do()"><ng-content></ng-content> <!-- Placeholder for dynamic content --></button>
Here, each <button> element uses ng-content to allow dynamic content to be passed into it. The content inside each button is projected when the component is rendered.
Step 4: Add CSS styles for the button component
Here are some basic styles for the buttons to make them visually appealing:
button {padding: 10px 20px;font-size: 16px;color: white;background-color: #007bff;border: none;border-radius: 5px;cursor: pointer;}button:hover {background-color: #0056b3;}
Step 5: Using the Button component
Now, we’ll use the ButtonComponent in our main application component.
import { Component } from '@angular/core';@Component({selector: 'app-root',templateUrl: './app.component.html',styleUrls: ['./app.component.css']})export class AppComponent {}
Step 6: Update the HTML file
Let’s update the HTML of our main application to use the button component.
<div style="text-align: center;"><h1>Dynamic Buttons Example with ng-content</h1><!-- Using the ButtonComponent with dynamic content --><btn>This is a dynamic Button Label</btn><btn>Click Me!</btn><btn>Submit Form</btn></div>
Application demo
Let’s see the output in the playground below:
This code adds a dynamic value to the label for the button when parsing the ButtonComponent. This will allow us to reuse the component wherever needed. Once the app is running, we’ll see three buttons with different labels, each clickable, and when clicked, the console will log "Button clicked!". This shows how to structure an Angular app with external HTML and CSS files.
By using ng-content, we can quickly and easily reuse the button component without having to create multiple components or duplicate code.
Note: Angular will know what text to place inside the label and will, therefore, display the content to the users.
Some tips for using ng-content
Use
ng-contentto quickly execute reusable code in multiple places without having to set up.Use multiple
<ng-content>tags in a single component to project different parts of the parent content in various locations within the child component.Remember that the styles defined in the parent component can affect the projected content. Use encapsulation strategies (like
ViewEncapsulation) to manage style scope.If the content doesn’t appear as expected, check the selector used in
<ng-content>tags and ensure that the projected content matches those selectors.Overusing content projection can lead to complex nested structures that might impact performance. Use it judiciously, especially in larger applications.
Summary
Using ng-content in Angular allows for the creation of highly reusable and maintainable components. It enhances our application’s structure by allowing dynamic content to be inserted into components without modifying their internal code. Whether we’re creating buttons, cards, or any other component, ng-content enables us to manage content efficiently.
Frequently asked questions
Haven’t found what you were looking for? Contact Us
What is the use of ng-content in Angular?
What is _ngcontent?
What is the difference between ng-content and ng-container in Angular?
How to use ng in Angular?
Free Resources