Getting value from another component

Viewed 50

Is there a possibility I can pass an event to other components without getting the selector of the component?

1 Answers

yes, the most popular solution is to use a service, inject it into both components, and create props on the service so u can store data on it , now you can access these props from both components, you should also use 'BehaviorSubject' so you can subscribe if data changed.

here is an example for it

Using Behavior Subject with Rxjs

I wrote an example for you

Service

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

@Injectable({
  providedIn: 'root'
})
export class ShareDataService {
 public sharedData :BehaviorSubject<number>= new BehaviorSubject(0);
  constructor() { }
}

First Component (will change data)

import { Component, OnInit } from '@angular/core';
import { ShareDataService } from '../share-data.service';

@Component({
  selector: 'app-first',
  templateUrl: './first.component.html',
  styleUrls: ['./first.component.css']
})
export class FirstComponent implements OnInit {

  firstModel: number;
  constructor(private dataService: ShareDataService) {
  }

  ngOnInit() {

  }
  changeDataOnTheSecondComp(input) {
    console.log(input);
    this.dataService.sharedData.next(input.value)
  }
}

will receive changed data

import { Component, OnInit } from '@angular/core';
import { ShareDataService } from '../share-data.service';
import { Subject } from 'rxjs';

@Component({
  selector: 'app-second',
  templateUrl: './second.component.html',
  styleUrls: ['./second.component.css']
})
export class SecondComponent implements OnInit {

  secondModel: number;
  constructor(private dataService: ShareDataService) {
  }

  ngOnInit() {
    this.dataService.sharedData.subscribe(x => {
      this.secondModel = x;
    })
  }

}
Related