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<any>();
sendMessage(message: string) {
this.subject.next({ text: message });
}
clearMessages() {
this.subject.next();
}
getMessage(): Observable<any> {
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);
})
}
}
You can create a service to share the data between components,
A new service called, filter-panel.service.ts
file with setter() and getter() method,
import { Injectable } from '@angular/core';
@Injectable()
export class FilterPanelService {
filterdata: any[];
constructor() { }
get data(): any{
return this.filterdata;
}
set data(val: any){
this.filterdata = val;
console.log(this.filterdata);
}
}
In filter-panel.component.ts
set the value like,
export class FilterPanelComponent implements OnInit {
public activeFilters: string[];
public text: string="hello world";
constructor(public filterPanelService:FilterPanelService) {
this.activeFilters = [
'Provider: CMS',
'Region: All',
'Provider Group:All',
'Provider: CMS',
'Region: All',
'Provider Group: All'
];
this.filterPanelService.data = this.activeFilters;
}
ngOnInit() {}
}
And in filter-bar.component.ts
get the value like,
export class FilterBarComponent implements OnInit {
@ViewChild('FilterPanelComponent', {static : false}) filterPanel: FilterPanelComponent;
public values1: string[] = ['Philips'];
public values2: string[];
constructor(public filterPanelService: FilterPanelService) {
//this.values2=this.filterPanel.activeFilters;
}
ngOnInit() {
//console.log(this.values2);
console.log('value received ', this.filterPanelService.data);
}
}
Working Stackblitz..