Search⌘ K
AI Features

Passing Data Between Unrelated Components

Explore how to pass data between unrelated Angular components by using shared injectable services. Learn to create a service with state, inject it into components, and update shared data dynamically, leveraging Angular's singleton design pattern for data consistency across components.

The final way of passing data between components is used for components that are unrelated – that is, components that don’t have this parent/child relationship.

Using shared services

Passing data between unrelated components can be done through shared services. The following is a service that contains some data:

import { Injectable } from "@angular/core";

@Injectable()
export class DataService {
  private message: string;
  constructor() {}
  changeMessage(newMessage: string) {
    this.message = newMessage;
  }
  getMessage(): string {
    return this.message;
  }
}

This service simply contains a private property called message, which can be changed ...