Angular Sharing Data between Two Different Components Using Child Routes(Learn It In 21 Steps)
Hey Everyone !!!, Thanks for visiting my medium I hope you doing well. Please find the below steps to implement the sharing data between two components using Routing in the angular application.
0. Before starting the application, you need to know about Routing in angular.
We are using routing for categorizing the components in form of pages in that way users can understand easily and remember easily. Also, Routing is used for lazy load the modules in angular. we can’t complete the angular application without routing and If you deal with only components the logic will be lengthy and it is not a good practice.
In Routing, by using paths we can categorize the components, and by using children we can include child routes inside the parent route.
I think you understood something, In the below example am using the child routes concept in routing to pass the data from one component to another component. For more information, please visit the official angular.io website.
- Create an angular project with the below command.
ng new angular-child-routes-simple-example
2. After successful creation of the angular app, change the file directory to project-name. by using the below command
cd angular-child-routes-simple-example
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 the browser 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 components of the user’s list, and user details components under the components folder, and also create user service under the apis folder by using the below commands.
ng generate component users-list
ng generate component user-details
ng generate service user
6. Install the bootstrap library by using the below command and also import the URL inside styles.scss file to load the bootstrap styles inside the application. If you had done already, please ignore this step.
npm install bootstrap
- Import the bootstrap in styles.scss file as below
@import ‘../node_modules/bootstrap/dist/css/bootstrap.min.css’;
7. After successfully creating the above files. Open app.module.ts, import HttpClientModule, and add it to the imports array like below.
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { UserDetailsComponent } from './components/user-details/user-details.component';
import { UsersListComponent } from './components/users-list/users-list.component';
import { UsersService } from './apis/users.service';
import { HttpClientModule } from '@angular/common/http';@NgModule({
declarations: [
AppComponent,
UserDetailsComponent,
UsersListComponent
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule
],
providers: [UsersService],
bootstrap: [AppComponent]
})
export class AppModule { }
8. After that open “users.service.ts” and import “HttpClient”, and also add it as a dependency inside the constructor.
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';@Injectable({
providedIn: 'root'
})
export class UsersService {public uri ='https://letstalk-be.herokuapp.com'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) { }
}
9. After that Add two service methods, loadUsers and loadUsersById to call the user’s endpoint.
- Here loadUsers() is to loads all the users from the service.
- Here loadUsersById(id) is to load single user by user-id.
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';@Injectable({
providedIn: 'root'
})
export class UsersService {public uri ='https://letstalk-be.herokuapp.com'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) { }public loadUsers(){
return this.http.get(`${this.uri}/public/users`,{headers :this.headers})
}public loadUsersById(id){
return this.http.get(`${this.uri}/public/users/${id}`,{headers :this.headers})
}
}
10. Finally, we have completed the service level part, after that we need to go for the view part (view logic).
Open the “app-routing.module.ts” file in vs code by using Ctrl + P and add the routing paths with child routes.
11.Open “users-list.component.html”, Add add the router outlet to display the user-details component. As you already know the user-details component is a child route to the users-list component.
The router outlet’s job is to display the content-related router. It will display the content based on path changes.
<div class="container row mt-3 ml-3">
<div class="col-md-4">
<!-- User-list component data displayed here-->
</div>
<div class="col-md-6">
<router-outlet>
<!-- users-list children routes data displayed here -->
</router-outlet>
</div>
</div>
12. Open “users-list.component.ts”, import the user service and add it as a dependency inside the constructor. Also, import the Router and add it as a dependency inside the constructor to perform navigation.
import { Component, OnInit} from '@angular/core';
import { UsersService } from 'src/app/apis/users.service';@Component({
selector: 'app-users-list',
templateUrl: './users-list.component.html',
styleUrls: ['./users-list.component.scss']
})
export class UsersListComponent implements OnInit {constructor(private api: UsersService) { }public ngOnInit(): void {
}
}
13. After that add usersData, and selectedUserId variables to store the user’s data and selected user values.
Here, variable usersData stores users’ data, and variable selectedUserId to store the selected user data to highlight the li element inside users-list.component.html.
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { UsersService } from 'src/app/apis/users.service';@Component({
selector: 'app-users-list',
templateUrl: './users-list.component.html',
styleUrls: ['./users-list.component.scss']
})
export class UsersListComponent implements OnInit {public usersData:any;
public selectedUserId="-1";constructor(private api: UsersService, private router: Router) { }public ngOnInit(): void {
}
}
14. After that add the “loadUsers” method to call the service method to get the data and store the user’s data inside the “usersData” variable. Also, call the loadUsers method from ngOnInit().
import { Component, EventEmitter, OnInit, Output, ViewChild } from '@angular/core';
import { Router } from '@angular/router';
import { UsersService } from 'src/app/apis/users.service';
import { UserDetailsComponent } from '../user-details/user-details.component';@Component({
selector: 'app-users-list',
templateUrl: './users-list.component.html',
styleUrls: ['./users-list.component.scss']
})
export class UsersListComponent implements OnInit {public usersData:any;
public selectedUserId="-1";constructor(private api: UsersService,private router: Router) { }public ngOnInit(): void {
this.loadUsers();
}public async loadUsers(){
const res = await this.api.loadUsers().toPromise().then((res:any) => res.users);
this.usersData = res;
}
}
15. Create a selectedUser method to call the router navigation and pass the user-id to the user-details component in a below way. Parallelly update the selectedUserId value based on user selection.
import { Component, EventEmitter, OnInit, Output, ViewChild } from '@angular/core';
import { Router } from '@angular/router';
import { UsersService } from 'src/app/apis/users.service';
import { UserDetailsComponent } from '../user-details/user-details.component';
@Component({
selector: 'app-users-list',
templateUrl: './users-list.component.html',
styleUrls: ['./users-list.component.scss']
})
export class UsersListComponent implements OnInit {
public usersData:any;
public selectedUserId="-1";
constructor(private api: UsersService,private router: Router) { }
public ngOnInit(): void {
this.loadUsers();
}
public async loadUsers(){
const res = await this.api.loadUsers().toPromise().then((res:any) => res.users);
this.usersData = res;
}
public selectedUser(user){
this.selectedUserId = user?._id
this.router.navigate(['users', this.selectedUserId]);
}
}
16. Oops !!!, Not added HTML inside the users.component.html. Add the below HTML to see the changes inside the Browser UI.
<div *ngIf="usersData" class="container row mt-3 ml-3">
<h3 class="mb-3">List of Users</h3>
<div class="col-md-4">
<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>
<div class="col-md-6">
<router-outlet></router-outlet>
</div>
</div>
17. Up to here, we have completed the one-component view (users-list component), and the users-details component is only pending (Need to add activate route and get the param from routing and call the service store the details inside one variable). If you did anything wrong, please go through all the above steps.
18. Open users-details.component.ts, import the user service, and add it as a dependency inside the constructor. Also, import the ActivatedRoute and add it as a dependency inside the constructor to get the parameters from the router path.
import { Component, Input, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { UsersService } from 'src/app/apis/users.service';@Component({
selector: 'app-user-details',
templateUrl: './user-details.component.html',
styleUrls: ['./user-details.component.scss']
})
export class UserDetailsComponent implements OnInit {
public usersDetails:any;constructor(private api: UsersService, private activatedRoute: ActivatedRoute) { }public ngOnInit(): void {
}
}
By Using ParamMap to get the router parameters from the activated route. Add the related code inside the ngOnInit method. Open the browser by using localhost:4200 and check whether the console user id is displayed or not by clicking on different users multiple times.
import { Component, Input, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { UsersService } from 'src/app/apis/users.service';@Component({
selector: 'app-user-details',
templateUrl: './user-details.component.html',
styleUrls: ['./user-details.component.scss']
})
export class UserDetailsComponent implements OnInit {
public usersDetails:any;constructor(private api: UsersService,private activatedRoute:ActivatedRoute) { }public ngOnInit(): void {
this.activatedRoute.paramMap.subscribe((params)=>{
if(params && params.get('id').toString()){
console.log(params.get('id').toString())
}
})
}
}
19. After that, create a usersDetails variable to store the user details and call and create loadUsersById method to call the service to get the user details based on user-id and also call the loadUsersById method from ngOnInit in the following way.
import { Component, Input, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { UsersService } from 'src/app/apis/users.service';@Component({
selector: 'app-user-details',
templateUrl: './user-details.component.html',
styleUrls: ['./user-details.component.scss']
})
export class UserDetailsComponent implements OnInit {
public usersDetails:any;constructor(private api: UsersService,private activatedRoute:ActivatedRoute) { }public ngOnInit(): void {
this.activatedRoute.paramMap.subscribe((params)=>{
if(params && params.get('id').toString() !== 'users'){
this.loadUsersById(params.get('id').toString())
}
})
}public async loadUsersById(value){
const res = await this.api.loadUsersById(value).toPromise().then((res:any) => res.user);
this.usersDetails = res;
}}
Here, the thing is whenever you select the user then the router path will update automatically.
20. After that add the Html code to display selected user-details inside the browser UI.
<div *ngIf="usersDetails">
<h2>Hi {{usersDetails.firstName | titlecase}} {{usersDetails.secondName | titlecase}}</h2>
<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">
<h5 style="color: red;">OOPS!!! User Not Selected, Please Select Any User</h5>
</div>
21. After everything is done, do “npm install” and “ng serve” to see changes open the project by using localhost:4200. If you did anything wrong please check properly from step 1.
Output:
SOURCE CODE:
Front End:
GitHub: https://github.com/mryenagandula/angular-child-routes-simple-example
Back End:
GitHub: https://github.com/mryenagandula/Letstalk-Backend
Live Backend URI: https://letstalk-be.herokuapp.com/
Stack blitz Project Preview:
https://stackblitz.com/edit/angular-child-routes-simple-example
T hanks 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 do share my story with your near and dear, Also follow and subscribe to the medium.