Child Components In Angular

Child Components In Angular

In this article, we will learn about how to add a child component to our Angular application. To create a new Angular project, we use the Angular CLI command ng new. It produces AppComponent, which is the application's main component. Using the selector <app-root>, the AppComponent is bootstrapped in the AppModule and loaded in the index.html file. <app-root>Loading...</app-root>. Let's add another component to the program in this article.

What is a Child Component

Each Angular Component oversees a distinct activity or workflow in Angular component-based architecture. Each Component is a reusable unit's independent block.

Many Angular Components will be present in real-world Angular apps. The root component's sole purpose is to host these child components. These child components, in turn, can host further child components, forming a Component Tree-like structure.

In this article, we will learn how to create a child or nested component and add it to the App Component.

Create a new application

Using the following command, create a new Angular application.

ng new child-component

How to add Child Component

  1. Create the Child Component by following the steps below. Metadata in the child Component specifies the selector to be used.
  2. In the module class, import the Child Component and declare it in the declaration Array.
  3. In the Parent Component Template, use the CSS Selector to designate where you want the Child Component to appear.

Adding a Child Component in Angular

Let's finish up by adding a Child Component to our app. Let's show a list of customers in our child component.

Make a child component.

The Child Component is created in the same way as any other Parent Component. But first, we'll need to create a customer.ts class.

Customer Class

Create a file with the name customer.ts in the app folder and add the code below.
export class Customer {
  customerNo: number;
  name:string ;
  address:string;
  city:string;
  state:string;
  country:string;
}

It's worth noting that we've used the export keyword. Importing the above class allows us to use it in our components.

Create Child Component

Create a new component called customer-list the using following command.
ng g c customer-list

Now, Open the component-list.component.ts and add the following code:
import { Component } from '@angular/core';
import { Customer } from './customer';
 
@Component({
  selector: 'customer-list',
  templateUrl: './customer-list.component.html'
})
export class CustomerListComponent
{
  customers: Customer[] = [
 
    {customerNo: 1, name: 'Rahuld Dravid', address: '', city: 'Banglaore', state: 'Karnataka', country: 'India'},
    {customerNo: 2, name: 'Sachin Tendulkar', address: '', city: 'Mumbai', state: 'Maharastra', country: 'India'},
    {customerNo: 3, name: 'Saurrav Ganguly', address: '', city: 'Kolkata', state: 'West Bengal', country: 'India'},
    {customerNo: 4, name: 'Mahendra Singh Dhoni', address: '', city: 'Ranchi', state: 'Bihar', country: 'India'},
    {customerNo: 5, name: 'Virat Kohli', address: '', city: 'Delhi', state: 'Delhi', country: 'India'},
 
  ]
}

We begin by importing the necessary modules and classes. Customer class is required by our component, therefore we import it along with the Component.
import { Component } from '@angular/core';
import { Customer } from './customer';

The @Component directive is the next stage. Customer-list is the value of the selector clause. To display our view, we must use this in our parent view. Customer-list.component.html is the templateURL, which we have yet to create.
@Component({
  selector: 'customer-list',
  templateUrl: './customer-list.component.html'
})

The Component class must be created as the final step. CustomerListComponent is the name we've given it. There is only one property in the class, which is a collection of customers. The customers collection is set up with some default data. You'll use the HTTP Client to receive data from the back-end server in real-world scenarios.
export class CustomerListComponent
{
  customers: Customer[] = [
 
    {customerNo: 1, name: 'Rahuld Dravid', address: '', city: 'Banglaore', state: 'Karnataka', country: 'India'},
    {customerNo: 2, name: 'Sachin Tendulkar', address: '', city: 'Mumbai', state: 'Maharastra', country: 'India'},
    {customerNo: 3, name: 'Saurrav Ganguly', address: '', city: 'Kolkata', state: 'West Bengal', country: 'India'},
    {customerNo: 4, name: 'Mahendra Singh Dhoni', address: '', city: 'Ranchi', state: 'Bihar', country: 'India'},
    {customerNo: 5, name: 'Virat Kohli', address: '', city: 'Delhi', state: 'Delhi', country: 'India'},
 
  ]
}

Now, Open the component-list.component.ts and add the following code:
<h2>List of Customers</h2>
 
<table class='table'>
  <thead>
    <tr>
      <th>No</th>
      <th>Name</th>
      <th>Address</th>
      <th>City</th>
      <th>State</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let customer of customers;">
      <td>{{customer.customerNo}}</td>
      <td>{{customer.name}}</td>
      <td>{{customer.address}}</td>
      <td>{{customer.city}}</td>
      <td>{{customer.state}}</td>
    </tr>
  </tbody>
</table>

The ngFor Directive offered by Angular was used to loop through the Customer collection. The ngFor Directive is covered in detail in a separate lesson.

The ngFor directive syntax begins with *ngFor. It is a structural instruction, as indicated by the *. i.e. a directive that inserts or removes HTML components from the Document Object Model (DOM).

*ngFor is assigned the expression let customer of customers. The let clause assigns the template reference variable or local variable customer an instance of the customer object from the customer collection.

To generate the template that displays the customer details to the user, we use the template reference variable customer. The ngFor directive is used on the table's tr element. Everything in the DOM tree is repeated by Angular inside the tr element.

In Angular, {{customer.customerNo}} stands for interpolation. Angular evaluates everything in the and substitutes the result for the string.

Import the Child Component in the Module

Each component, directive, and pipe that we create must be part of an Angular Module. To accomplish this, we must first register our component with the Module. A component, directive, or pipe can only be used in one module.

Angular Modules (or NgModules) are a mechanism for Angular to bring together related components, directives, pipes, and services, among other things. To add a component to an Angular Module, you must declare it in the declarations metadata.

When we create a new Angular app, Angular creates a top-level root module (AppModule in file app.module.ts). That's where our CustomerListComponent needs to be registered.

Now, Open the app.module.ts and add the following code:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
 
import {NgbModule} from '@ng-bootstrap/ng-bootstrap';
 
import { AppComponent } from './app.component';
import {CustomerListComponent} from './customer-list.component';
 
@NgModule({
  declarations: [
    AppComponent, CustomerListComponent
  ],
  imports: [
    BrowserModule,NgbModule.forRoot()
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

There are two phases to registering a component or directive in a module.

Now, import it.
import { AppComponent } from './app.component';
import {CustomerListComponent} from './customer-list.component';

@NgModule({
declarations: [
   AppComponent, CustomerListComponent
]

Finally, we must inform Angular where the child Component should be displayed.

We want our child Component to be the AppComponent's child. Add the following template to the app.component.html file.
<h1>{{title}}. </h1>
 
<customer-list></customer-list>
In the metadata for the CustomerListComponent, we used the customer-list as the selector in the @Component decorator. The element tag given in the parent component's template must match this CSS selector name.
<customer-list></customer-list>

Now, run the application using ng Serve

Conclusion
In this article, we learned how to add a child component to our application. In next article we learn about the Directives In Angular.

I hope this article helps you and you will like it.👍

If you have any doubt or confusion then free to ask in comment section.

Post a Comment

Previous Post Next Post