DEV Community

Cover image for Communicate between Angular components
Nicolas LARRODE
Nicolas LARRODE

Posted on

1 1

Communicate between Angular components

Angular v10.0.9

The first time I had to communicate between two Angular components, it was Parent/child relation, and it's pretty easy with @output and @input.

But the first time I had to, without this relation, I was completely lost.

Create a Service

We assume you have now two components, not connected by any relationship, let's create a new service :

ng g service <name>

name it like you want !

The generated Service looks like :

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

@Injectable({
  providedIn: 'root'
})
export class DataService {
  // Your code here
}

Subject

We will use Subject, a special type of Observable that allows values to be multicasted to many Observers !

Import Subject from rxjs in your Service :

import { Subject } from 'rxjs'

Now we can create a Subject to carry the data to share between our components :

data: Subject<Type> = new Subject();

Subject can be any Typescript type

It's Done !

Yeah, really.

You have just to import the service into your components with :

import { dataService } from "../services/data.service";

+

constructor(
    private sharedData: dataService,
  ) {}

To get the data

this.sharedData.data.subscribe(data => {
     //Do what you want with data 
})

data will be updated automatically

To set the data :

this.sharedData.data.next(newValue)

The data will be updated in ALL your components wich have subscribed to the value

nik0w image

Thanks for reading! Was this article helpful for you? Any ideas that can be shared? Post a comment below!

P.S. This is my first Angular post, I hope you will love it !

Tiugo image

Modular, Fast, and Built for Developers

CKEditor 5 gives you full control over your editing experience. A modular architecture means you get high performance, fewer re-renders and a setup that scales with your needs.

Start now

Top comments (0)

Neon image

Next.js applications: Set up a Neon project in seconds

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Get started →

👋 Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay