Bhushan Gadekar
Bhushan Gadekar

Reputation: 13805

angular2- how to communicate between two separate components?

I am working on this angular2 project. I have 2 components i.e. WorkspacesComponent & PagesComponent.

in database,each workspace contains number of pages. I have written below code to populate list of workspaces in workspacesComponent & list of pages in PagesComponent.

getting workspaces from database

 this.workspaceService.getAllWorkspaces(this.baseUrl)
        .subscribe((workspaces) => {
            this.workspaces = workspaces;
            console.log(this.workspaces);
        }
        );

getting pages from databases

this.pagesService.getAllpages(this.baseUrl)
        .subscribe((pages) => {
            this.pages = pages;
            console.log(this.pages);
        }
        );

so far , they are returning me correct data.but I want to implement the functionality where I will be selecting workspace in workspaceComponent & all the pages in that workspace only should be listed in pagesComponent.

Expected result

that is, on click of workspace, its index can be passed to below method.

getPagesByWorkspaceId(index:string){
    console.log(index);
}

and this method will load the list of pages in that workspace accordingly. the problem is that I am not sure how to call a method in PagesComponent from WorkspacesComponent

any inputs?

Upvotes: 1

Views: 3099

Answers (2)

Thierry Templier
Thierry Templier

Reputation: 202296

If there is no relation (parent/child) between your two components, you need to leverage a shared service.

See this question for more details:

This link from the angular doc could also help you:

Upvotes: 1

Günter Zöchbauer
Günter Zöchbauer

Reputation: 658017

For communication between components that are not in a direct parent-child relationship use a shared service to share data and communicate.

For more info see https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service

Upvotes: 1

Related Questions