Here’s a complete example demonstrating how to create two components (HomeComponent and CounterComponent), navigate between them using a navigation bar, and communicate between them via a shared service. The shared service will allow data communication from one component to the other through event handling.
1. Create the Angular Project and Components
Start by creating a new Angular project (if not already created) and generate the components:
ng new angular-communication-example - standalone
cd angular-communication-example
# Generate HomeComponent and CounterComponent
ng generate component home - standalone
ng generate component counter - standalone
2. Create the Shared Service
Generate a shared service that will handle communication between the components:
ng generate service shared
Implement the shared service (shared.service.ts):
// src/app/shared.service.ts
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class SharedService {
private messageSource = new BehaviorSubject<string>('Default Message');
currentMessage = this.messageSource.asObservable();
changeMessage(message: string) {
this.messageSource.next(message);
}
}
3. Implement HomeComponent
Modify HomeComponent to send data via the shared service.
// src/app/home/home.component.ts
import { Component } from '@angular/core';
import { SharedService } from '../shared.service';
@Component({
standalone: true,
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent {
constructor(private sharedService: SharedService) {}
onButtonClick() {
this.sharedService.changeMessage('Hello from HomeComponent!');
}
}
// Update home.component.html:
// src/app/home/home.component.html
<div class="home-container">
<h2>Home Component</h2>
<button (click)="onButtonClick()">Send Message to Counter Component</button>
</div>
4. Implement CounterComponent
Modify CounterComponent to receive and display the data from the shared service.
// src/app/counter/counter.component.ts
import { Component, OnInit } from '@angular/core';
import { SharedService } from '../shared.service';
@Component({
standalone: true,
selector: 'app-counter',
templateUrl: './counter.component.html',
styleUrls: ['./counter.component.css']
})
export class CounterComponent implements OnInit {
message: string = '';
constructor(private sharedService: SharedService) {}
ngOnInit(): void {
this.sharedService.currentMessage.subscribe(message => {
this.message = message;
});
}
}
// Update counter.component.html:
// src/app/counter/counter.component.html
<div class="counter-container">
<h2>Counter Component</h2>
<p>Message from Home Component: {{ message }}</p>
</div>
5. Update AppComponent
Implement AppComponent to include the navigation bar and router outlet.
// src/app/app.component.ts
import { Component } from '@angular/core';
import { RouterModule } from '@angular/router';
@Component({
selector: 'app-root',
standalone: true,
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
imports: [RouterModule]
})
export class AppComponent {
title = 'Angular Communication Example';
}
// src/app/app.component.html
<nav>
<ul>
<li><a routerLink="/home" routerLinkActive="active">Home</a></li>
<li><a routerLink="/counter" routerLinkActive="active">Counter</a></li>
</ul>
</nav>
<router-outlet></router-outlet>
6. Configure the Routing
Update the main.ts to set up the routing for the application.
// src/main.ts
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app/app.component';
import { provideRouter, Route } from '@angular/router';
import { HomeComponent } from './app/home/home.component';
import { CounterComponent } from './app/counter/counter.component';
const routes: Route[] = [
{ path: 'home', component: HomeComponent },
{ path: 'counter', component: CounterComponent },
{ path: '', redirectTo: 'home', pathMatch: 'full' },
];
bootstrapApplication(AppComponent, {
providers: [provideRouter(routes)],
}).catch(err => console.error(err));
7. Run the Application
Now, run the application to see the communication in action:
ng serve
When you navigate to the “Home” component and click the button, it sends a message to the SharedService, which is then displayed in the “Counter” component when you navigate there.
Summary
- The shared service uses a BehaviorSubject to store and emit messages.
- The HomeComponent updates the message through the service.
- The CounterComponent subscribes to the message observable and displays the updated message.
- The navigation bar is used for routing between components.