How to share data between child and parent components in Angular Part 1

The two components may have a parent-child or shibling relationship. A parent module send the data to child component using @Input decorator and child component share data to parent component using @Outupt decorator.

In this article, we will go through example of sharing data between parent controller and child controller. In a prevous article, have already a simple example how to two-way bind. In this article, we will create two component child and parent will share data between them.

Here is screenshot how it will look after completion:

So lets start from configuring new Angular application. After you create new Angular application, follow the below steps:

Step 1: Change index.html view

First of all, we need to change our main template index.html in /src folder. We are using Bootstrap for designing views so we don't need to write extra CSS in component. The main tag <app-root></app-root> will render HTML code from app.module.html.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Child</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
  <div class="container mt-5">
    <div class="row">
      <div class="col-12">
        <h1>Parent/child component example</h1>
        <app-root></app-root>
      </div>
    </div>
  </div>
  <script type="text/javascript" src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>

Step 2: change in app.module.html

Now we will remove all code from main HTML file app.component.html from /src/app directory. Only keep the tag for parent component which we will create in Next step.

<app-parent></app-parent>

Step 3: Create parent component.

Run the following ng command to generate new component.

ng generate component parent

This will generate parent component directory. Now run the Angular server with following command and it will open Angular application in default browser.

ng serve --open

You can see the parent component view in Browser.

Step 4: create random data.

We need some random data which we will display and pass from parent component to child component. So Create users varialbe ParentComponent class.

src/app/parent/parent.component.ts file

export class ParentComponent implements OnInit {

  users: any = [
    {id: 1, name: 'Jitesh Meniya', email: '[email protected]' },
    {id: 2, name: 'Hardik Savani', email: '[email protected]' },
    {id: 3, name: 'Harsukh Makwana', email: '[email protected]' }
  ];

  constructor() { }

  ngOnInit(): void {
  }
}

Step 5: displaying data in a view

Now we have users variable availalbe in the HTML view that we will render in the table using for loop. Add the below code in src/app/parent/parent.component.html file

<table class="table table-hover">
  <thead>
    <tr>
      <th scope="col">ID</th>
      <th scope="col">Name</th>
      <th scope="col">Email</th>
      <th scope="col">Aciton</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let user of users">
      <td>{{ user.id }}</td>
      <td>{{ user.name }}</td>
      <td>{{ user.email }}</td>
      <td>
        <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#modal">Show</button>
      </td>
    </tr>
  </tbody>
</table>
<div class="modal fade" id="modal" tabindex="-1" aria-labelledby="modalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="modalLabel">Modal title</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <p>Hello World!</p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

It will render data in table and looks like this. We have added modal in the parent component for now which display static string. We will make it dynamic in the next step.

Explanation:

In the table view, we have iterated users array in <tbody> element. Angular's *ngFor directive iterate all items in array and render them in iteration.

Step 6: Displaying data over modal.

Now we need to display specific user data in the modal when we click on any user. So we have to create a property for selected user. Add a new property in ParentComponent class.

src/app/parent/parent.component.ts

export class ParentComponent implements OnInit {

  selectedUser?: any;

  ....

}

Next we will change its value to the user when we click on any user button. So we need to bind click event on button in table and pass user data to component. Add click event in the table button as follow:

src/app/parent/parent.component.html

<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#modal" (click)="onClick(user)">Show</button>

Create onClick() method ParentComponent class 

src/app/parent/parent.component.ts

export class ParentComponent implements OnInit {

  onClick(user: any) {
    this.selectedUser = user;
  }
}

In the in Modal body, change the static text to dynamic as follow. Wrap it will *ngIf directive so it only display it if the selectedUser exist.

parent.component.ts file

<div class="modal-body">
    <!-- <p>Hello World!</p> -->
  <div *ngIf="selectedUser">
    <div class="mb-3 row">
      <p>{{ selectedUser.name }}</p>
      <p>{{ selectedUser.email }}</p>
    </div>
  </div>
</div>

In the browser refresh the page and click on any button. The modal should display user data.

In the next article, we will add child component and move modal view to child component. We will also change these text to input fields.

Tags:

Was this article helpful?

0 out of 0 person found this article helpful.

Leave a comment

Or

No Comment