1

I have three components.

  • CategoryComponent - list of categories
  • ListComponent - list of elements of selected category
  • ScreenComponent - composition of MenuComponent and ContentComponent

The ScreenComponent template looks like:

<category-list></category-list>
<elements-list [categoryId]="6"></elements-list>

I want ListComponent to get ID of category selected in CategoryComponent instead of hardcoded 6. How can I do this? Is this correct approach or the CategoryComponent job should be done by ScreenComponent?

Lukasz Puchala
  • 466
  • 1
  • 6
  • 11

1 Answers1

0

Since there is no relation (parent / child) between these two components, you need to leverage a shared service. The elements list would register to an observable into the service to be notified when a category is selected and update itself accordingly.

This service could contain both data and observables to subscribe on to be notified when data are updated.

  • Service

    export class SharedService {
      observable: Observable<any>;
      observer: Observer<any>;
    
      constructor() {
        this.observable = new Observable.create(observer => {
          this.observer = observer;
        }).share();
    
      updateData() {
        this.observer.next('something');
      }
    }
    
  • Component

    @Component({
      selector: 'my-component1',
      template: `
        (...)
      `
    })
    export class MyComponent1 {
      constructor(private service:ListService) {
        this.service.observable.subscribe.(data => {
          (...)
        });
      }
    }
    
  • bootstrap

    bootstrap(AppComponent, [ SharedService ]);
    

See this question for more details:

Community
  • 1
  • 1
Thierry Templier
  • 198,364
  • 44
  • 396
  • 360