0

I have a top menu (Component) that displays a list of models, and a side menu (Component) that displays a list of colors. In the center of my page I have a table (Component) that displays a list of things based on the user selections of color and model controls. None of the controls is a child of any other. The table component is rendered in a router-outlet container.

How can I make the table component listen for property changes in the two menu components?

I have already tried a session service as described here: https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-servicehttps://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service

It does not work because the table component is not a child of the menu components.

1 Answer 1

3

I would make simple service for it:

@Injectable()
export class FilterService {
    public modelChange$:EventEmitter;
    public colorChange$:EventEmitter;

    constructor(){
        this.modelChange$ = new EventEmitter();
        this.colorChange$ = new EventEmitter();
    }

    public setModel(model):void{
        this.modelChange$.emit(model);
    }

    public setColor(color):void{
        this.colorChange$.emit(color);
    }
}

Then TopMenuComponent and SideMenuComponent will invoke the service's setters:

constructor(private _filterService:FilterService){}
// method invoked by user's action
onSelect(value) {
    this._filterService.setModel(value); // or setColor()
}

and TableComponent will subscribe for the events:

constructor(private _filterService:FilterService){
    this._filterService.modelChange$.subscribe(model => console.log("new model: " + model));
    this._filterService.colorChange$.subscribe(color => console.log("new color: " + color));
}

I used my interior artist to show how it would work: at least i tried to

Hope it helped.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.