I\'m new to Angular. I\'m trying a simple thing today. I\'ve gone through many answers but not able implement them correctly. I want to access some variables of filter-pan
If both component don't have parent child relationship and if you want to pass the data between them then you can implement the RxJS
subject for the same. I hope it helps you out
Message Service
import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs';
@Injectable({ providedIn: 'root' })
export class MessageService {
private subject = new Subject();
sendMessage(message: string) {
this.subject.next({ text: message });
}
clearMessages() {
this.subject.next();
}
getMessage(): Observable {
return this.subject.asObservable();
}
}
filter-panel.component.ts
import { Component, OnInit } from '@angular/core';
import { messageService } from '../MesssageService.ts'
@Component({
...
})
export class FilterPanelComponent implements OnInit {
public activeFilters: string[];
public text: string="hello world";
constructor(private messageService: MessageService) {
this.activeFilters = [
'Apple',
'Grapes',
'Bana'
];
}
ngOnInit() {}
this.messageService.sendMessage('data from filterPanelComponent'); // here you can also pass the object
}
filter-bar.component.ts
import { Component, OnInit, ViewChild } from '@angular/core';
import { messageService } from '../MesssageService.ts'
@Component({
...
})
export class FilterBarComponent implements OnInit {
constructor(private messageService: MessageService) {
}
ngOnInit() {
this.messageService.getMessage().subscribe(response => {
// here we get the data from another component
console.log(response);
})
}
}