Angular Sharing Data from Parent to Child Using @Input and @Output Directive (Learn It In 20 Steps)

Srikanth
6 min readAug 11, 2022

--

Please find the below steps to implement to share data between parent-to-child components using @input and @Output Directive in angular application.

Photo by Elaine Casap on Unsplash
  1. Create an angular project with the below command.
ng new angular-input-and-output

2. After successful creation of the angular app, change the file directory to project-name. by using the below command

cd angular-input-and-output

3. Open the project in vs code using “code .” or open with “vs code” after that run the project by using the “ng serve” command and Open the project in chrome using localhost:4200

4. Open the app component in vs code and remove the content created by angular CLI while developing the app.

5. Generate two components the users, the user’s list and user details component under the components folder, and create user service under the APIs folder by using the below commands.

ng generate component usersng generate component users-listng generate component users-detailsng generate service user-service

6. After successfully creating the files.

  • Open the “users.component.html” file in vs code by using Ctrl + P and add two-component selectors.
<div class="container mt-4">
<div class="row">
<app-users-list class="col-md-4"></app-users-list>
<app-user-details class="col-md-8"></app-user-details>
</div>
</div>
  • Also, add the users component in the app routing module file.
const routes: Routes = [
{
path:'users',
component: UsersComponent
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }

7. Open the application by using localhost:4200 to see the changes, You will see two components.

8. Open the user service file and add the below code to call the users, single user info from backend service.

private headers:HttpHeaders= new HttpHeaders({
'Content-Type':'application/json',
'Accept':"application/json",
'Access-Control-Allow-Methods':'GET,POST,PUT,DELETE',
'Authorization':''
});
constructor(private http:HttpClient) { }// To get all the users
public loadUsers(){
return this.http.get(`
http://localhost:3000/public/users`,{headers :this.headers})
}
// To get the single user info
public loadUsersById(id){
return this.http.get(`
http://localhost:3000/public/users/${id}`,{headers :this.headers})
}

9. Open the users-list component and import the user service and add it as a dependency in the constructor like below.

import { UsersService } from 'src/app/apis/users.service';constructor(private api: UsersService) { }

10. After that create a variable usersData for storing users. Create a loadUsers() method to call the service to load all the users. And also call the load Users method in side the ngOnInit().

public usersData:any;constructor(private api: UsersService) { }public ngOnInit(): void {
this.loadUsers();
}
public async loadUsers(){
const res = await this.api.loadUsers().toPromise().then((res:any) => res.users);
this.usersData = res;
}

11. Opps not added HTML content to display the user’s data, For that add below HTML code.

<div *ngIf="usersData">
<ul class="list-group" style="min-height: 400px;overflow-y: auto;height: 400px;">
<li
class="list-group-item"
*ngFor="let user of usersData"
[ngClass]="{'active': selectedUserId === user._id}"
(click)="selectedUser(user)"
>
{{user.firstName}} {{user.secondName}} <strong>(@{{user.userName}})</strong>
</li>
</ul>
</div>

12. After that just check the changes by opening the application in the side browser using localhost:4200 and check it properly, If you found anything wrong please check all the steps. Do n

13. Open the user-details component and import the user service file and add it as a dependency in the constructor.

import { UsersService } from 'src/app/apis/users.service';constructor(private api: UsersService) { }

14. Create a variable usersDetails to store the selected user info and create the loadUserById() method and add logic to call the service.

public usersDetails:any;constructor(private api: UsersService) { }public ngOnInit(): void {}public async loadUsersById(value){
const res = await this.api.loadUsersById(value).toPromise().then((res:any) => res.user);
this.usersDetails = res;
}
  • Add Html code inside the user-details component to load the user details,
<div class="p-2" *ngIf="usersDetails">
<h1>Hi {{usersDetails.firstName}} {{usersDetails.secondName}}</h1>
<p>Username : @{{usersDetails.userName}}</p>
<p>Mobile : {{usersDetails.mobile}}</p>
<p>DOB : {{usersDetails.dob}}</p>
<p>Email Address : {{usersDetails.email}}</p>
<p>Email Verified : {{usersDetails.email_Verified ? "Yes" : "No"}}</p>
<p>Account Enabled : {{usersDetails.activated ? "Yes" : "No"}}</p>
<p>Gender : {{usersDetails.gender}}</p>
<p>Updated At: {{usersDetails.updatedAt | date:'medium'}}</p>
<p>Created At: {{usersDetails.createdAt | date:'medium'}}</p>
</div>
<div *ngIf="!usersDetails">
<h3 style="color: red;">OOPS!!! User Not Selected, Please Select Any User</h3>
</div>

15. As of now am not able to get the user id from the users-list component and In the users list component, we are not sending the user id to the user-details component. There is no relation between these components. For Sending the values from one component to another component by using @output and @Input decorators.

16. In this project we added a user-list and user-details selectors in the side users component. Whenever I am selected the user am sending the user Id from the users-list to the users component through the @Input decorator, After that same user id passes to the users-list component, In that way, the parent and child relationship will happen, Here the parent component is the Users Component and children will be users-list and user-details.

17. Open the users-list component and add the below changes in side users-list.component.ts and users-list.component.html.

  • The selectedUserId as the output emitter and create the selectedUser variable to highlight the row.
public selectedUserId="-1";@Output()
public selectUserDetails:any = new EventEmitter<any>();
  • Create a selectedUser method to emit the selected user id.
public selectedUser(user){
this.selectedUserId = user?._id;
this.selectUserDetails.emit(user?._id);
}
  • After that update the Html to highlight the row and add the selectedUser method.
<div *ngIf="usersData">
<ul class="list-group" style="min-height: 400px;overflow-y: auto;height: 400px;">
<li
class="list-group-item"
*ngFor="let user of usersData"
[ngClass]="{'active': selectedUserId === user._id}"
(click)="selectedUser(user)"
>
{{user.firstName}} {{user.secondName}} <strong>(@{{user.userName}})</strong>
</li>
</ul>
</div>

18. Open the users-details component and add the below changes.

  • Create a variable to store user details and to get the user-id from users component add @input decorator.
public usersDetails:any;@Input() public set selectedUser(value){
if(value){
this.loadUsersById(value);
}
}
  • Add below Html to display user details. If you added ignore this step.
<div class="p-2" *ngIf="usersDetails">
<h1>Hi {{usersDetails.firstName}} {{usersDetails.secondName}}</h1>
<p>Username : @{{usersDetails.userName}}</p>
<p>Mobile : {{usersDetails.mobile}}</p>
<p>DOB : {{usersDetails.dob}}</p>
<p>Email Address : {{usersDetails.email}}</p>
<p>Email Verified : {{usersDetails.email_Verified ? "Yes" : "No"}}</p>
<p>Account Enabled : {{usersDetails.activated ? "Yes" : "No"}}</p>
<p>Gender : {{usersDetails.gender}}</p>
<p>Updated At: {{usersDetails.updatedAt | date:'medium'}}</p>
<p>Created At: {{usersDetails.createdAt | date:'medium'}}</p>
</div>
<div *ngIf="!usersDetails">
<h3 style="color: red;">OOPS!!! User Not Selected, Please Select Any User</h3>
</div>

19***. Open the users component and add the below changes to build the relationship between the two components.

  • Create the selectUserDetails() method and selectedUser variable.
public selectedUser;
constructor() { }
ngOnInit(): void {}public selectUserDetails(value){
this.selectedUser = value;
}
  • Update the Html with input and event actions.
<div class="container mt-4">
<div class="row">
<app-users-list (selectUserDetails)="selectUserDetails($event)" class="col-md-4"></app-users-list>
<app-user-details class="col-md-8" [selectedUser]="selectedUser"></app-user-details>
</div>
</div>

20. After everything is done, Do npm install and ng serve to see changes open project by using localhost:4200.

Output :

Screen #1:

Screen #2:

SOURCE CODE:Front End:
GITHUB:
https://github.com/mryenagandula/angular-input-and-output
Back End:
GITHUB:
https://github.com/mryenagandula/Letstalk-Backend
Live Backend URI: https://letstalk-be.herokuapp.com/Stackblitz Project Preview: https://stackblitz.com/edit/github-angular-input-and-output

Thanks for reading my article, Please share your feedback, claps, and comments. In that way, it will be helped me to improve my articles in the future. Please share my story with your near and dear, Also follow and subscribe to the medium.

--

--

Srikanth

Senior Software Engineer | Medium Articles | Storyteller | Quick Learner | React JS | Angular | Java | Learn Something new from my stories