In Angular 2 (and later versions), you can use a shared Observable to implement a master-detail scenario where changes made in the detail component are reflected in the master component. To achieve this, you'll need to create a service that holds the shared data as an Observable, and both the master and detail components will subscribe to this Observable.

Here's an example of how you can do it:

  1. Create a service that holds the shared data as an Observable:
// data.service.ts import { Injectable } from '@angular/core'; import { BehaviorSubject, Observable } from 'rxjs'; @Injectable() export class DataService { private sharedDataSubject: BehaviorSubject<any> = new BehaviorSubject<any>(null); public sharedData$: Observable<any> = this.sharedDataSubject.asObservable(); updateSharedData(data: any) {; } }
  1. In the master component, subscribe to the sharedData$ Observable to receive updates:
// master.component.ts import { Component, OnInit } from '@angular/core'; import { DataService } from './data.service'; @Component({ selector: 'app-master', templateUrl: './master.component.html', }) export class MasterComponent implements OnInit { masterData: any; constructor(private dataService: DataService) {} ngOnInit() { this.dataService.sharedData$.subscribe((data) => { this.masterData = data; }); } }
  1. In the detail component, update the shared data through the DataService:
// detail.component.ts import { Component } from '@angular/core'; import { DataService } from './data.service'; @Component({ selector: 'app-detail', templateUrl: './detail.component.html', }) export class DetailComponent { constructor(private dataService: DataService) {} updateSharedData(data: any) { // Perform any logic or transformations on the data if needed this.dataService.updateSharedData(data); } }
  1. Now, when the updateSharedData() method is called in the detail component, it will update the shared data in the DataService, and the master component will receive the updated data through the subscription to sharedData$.

Remember to provide the DataService in the root AppModule or in a higher-level component that both the master and detail components share.

By using this shared Observable approach, you can achieve communication between master and detail components without tightly coupling them together, making it easier to manage data updates and maintain a clean architecture in your Angular application.

Have questions or queries?
Get in Touch