In this section, we are going to learn about Ng-containers. We can use any version of Angular like Angular 6, 7, 8, and Angular 8 in ng-content in our application. Here, we are going to use ng-content with ng-container.
Using the ng-container and ng-content, we can provide one more solution to the reusable components. In our Angular application, we can easily create a reusable component by using the ng-container and ng-content. In our component, we can easily pass data dynamically.
In our below example, the my-card component will be created. In order to create this, ng-content will be used with the ng-container. In our example, id and dom elements can also be used. We will also use Bootstrap 4. We will use it with content, title, and footer text. We can dynamically pass those parameters and call our component at any place in our Angular application. In order to create ng-container with ng-content, the step by step process is described as follows:
Step 1:
In this step, we are going to Create New App. The following will be used to create our new Angular app like this:
ng new appNgContent
Step 2:
In this step, we are going to Create New Component. For this, a new component named my-card will be created. Here, we will also use a Bootstrap card. We will use the view file and update it like this:
ng g component my-card
Now we will use a file named my-card.components.ts and update their code like this:
src/app/my-card/my-card.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'my-card',
templateUrl: './my-card.component.html',
styleUrls: ['./my-card.component.css']
})
export class MyCardComponent implements OnInit {
constructor() { }
ngOnInit() {
}
}
Here, the card layout of Bootstrap 4 will be used. If our system doesn’t have Bootstrap, we can use the following link to install it into our system:
Now we will use our HTML view file and update it like this:
src/app/my-card/my-card.component.html
<div class="card">
<div class="card-header">
<ng-content select=".header"></ng-content>
</div>
<div class="card-body">
<ng-content select=".content"></ng-content>
</div>
<div class="card-footer">
<ng-content select=".footer"></ng-content>
</div>
</div>
Step 3:
In this step, we are going to Use Components. Here, we will use the dynamic data and call our component like this:
src/app/app.component.html
<my-card>
<ng-container class="header">
Example of ng-container Select by Class using Angular
</ng-container>
<ng-container class="content">
Here, we will learn about ng-content using angular. We will also learn the use of ng-content in angular. This example is used to display ng-content select by class using Angular.
</ng-container>
<ng-container class="footer">
This example is from Javatpoint.com
</ng-container>
</my-card>
Now our above code is ready to run. In order to run the above code, we will use the following command:
ng serve
Leave a Reply