Angular5 - How to call the function of different component












1















I have a component with a template which makes a call to the function which is in other component.



<div class="collapse list-unstyled">
<div *ngFor="let data of data1; let i=index">
<li>
<a class="dropdown-item menu-item" (click)= menu(i) >
{{data.item}}
</a>
</li>
</div>


Here menu(i) is the function of other component.
So from this component I want to directly make the call to the function in the other component. Their is no parent-child relation between the components. What could be the preferable way for me to do it?










share|improve this question























  • Take a look at this, it may give you some ideas on how to handle this.

    – R. Richards
    Nov 15 '18 at 23:01
















1















I have a component with a template which makes a call to the function which is in other component.



<div class="collapse list-unstyled">
<div *ngFor="let data of data1; let i=index">
<li>
<a class="dropdown-item menu-item" (click)= menu(i) >
{{data.item}}
</a>
</li>
</div>


Here menu(i) is the function of other component.
So from this component I want to directly make the call to the function in the other component. Their is no parent-child relation between the components. What could be the preferable way for me to do it?










share|improve this question























  • Take a look at this, it may give you some ideas on how to handle this.

    – R. Richards
    Nov 15 '18 at 23:01














1












1








1








I have a component with a template which makes a call to the function which is in other component.



<div class="collapse list-unstyled">
<div *ngFor="let data of data1; let i=index">
<li>
<a class="dropdown-item menu-item" (click)= menu(i) >
{{data.item}}
</a>
</li>
</div>


Here menu(i) is the function of other component.
So from this component I want to directly make the call to the function in the other component. Their is no parent-child relation between the components. What could be the preferable way for me to do it?










share|improve this question














I have a component with a template which makes a call to the function which is in other component.



<div class="collapse list-unstyled">
<div *ngFor="let data of data1; let i=index">
<li>
<a class="dropdown-item menu-item" (click)= menu(i) >
{{data.item}}
</a>
</li>
</div>


Here menu(i) is the function of other component.
So from this component I want to directly make the call to the function in the other component. Their is no parent-child relation between the components. What could be the preferable way for me to do it?







angular






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 15 '18 at 22:12









user10648256user10648256

536




536













  • Take a look at this, it may give you some ideas on how to handle this.

    – R. Richards
    Nov 15 '18 at 23:01



















  • Take a look at this, it may give you some ideas on how to handle this.

    – R. Richards
    Nov 15 '18 at 23:01

















Take a look at this, it may give you some ideas on how to handle this.

– R. Richards
Nov 15 '18 at 23:01





Take a look at this, it may give you some ideas on how to handle this.

– R. Richards
Nov 15 '18 at 23:01












2 Answers
2






active

oldest

votes


















0














Ideally, in this situation you would not want to provide a component like you would normally provide a service, as the currently accepted answer suggests. You could/should use a shared service. I will suggest a shared service to allow the component to component communication you need.



First thing you will need is a common service that any component could get injected via the IoC container Angular makes available. It could look something like this:



import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';

@Injectable()
export class CommonService {
menuChoosen$ = new Subject<number>();

constructor() { }
}


Since you seem to be using Angular 5, you will need to provide this service from the app module.



import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppComponent } from './app.component';
import { OneComponent } from './one/one.component';
import { AnotherComponent } from './another/another.component';
import { CommonService } from './common.service';

@NgModule({
imports: [ BrowserModule, FormsModule ],
declarations: [ AppComponent,
OneComponent,
AnotherComponent,
YetAnotherComponent ],
providers: [ CommonService ], // HERE
bootstrap: [ AppComponent ]
})
export class AppModule { }


The CommonService service exposes a menuChoosen$ Subject that any component can subscribe to when it needs to know when a menu item has been chosen. In the component where the menu item is selected, you inject the common service, and call the next function on the Subject when a menu option is selected.



import { Component, OnInit } from '@angular/core';
import { CommonService } from '../common.service';

@Component({
selector: 'app-one',
templateUrl: './one.component.html',
styleUrls: ['./one.component.css']
})
export class OneComponent implements OnInit {
data1 = [{item: 'Menu Item 1 (index 0)'}, {item: 'Menu Item 2 (index 1)'}, {item: 'Menu Item 3 (index 2)'}];
constructor(private commonService: CommonService) { }

ngOnInit() { }
menu(index: number) {
this.commonService.menuChoosen$.next(index); // next fired here!!
}
}


The template for the OneComponent will look something like this:



<div *ngFor="let data of data1; let i=index">
<li (click)="menu(i)">{{data.item}} </li>
</div>


When a list item (menu item) is clicked, the index (i) value is sent to the menu function, which in turn calls the next function of the CommonService menuChoosen$ Subject.



Any other component that subscribes to the menuChoosen$ Subject will then be updated. In this case, the AnotherComponent is a subscriber, and will know about the event. See below.



import { Component, OnInit } from '@angular/core';
import { CommonService } from '../common.service';

@Component({
selector: 'app-another',
templateUrl: './another.component.html',
styleUrls: ['./another.component.css']
})
export class AnotherComponent implements OnInit {
chosenMenuIndex: number;
constructor(private commonService: CommonService) { }

ngOnInit() {
// the subscription starts below
this.commonService.menuChoosen$.subscribe(idx => {
this.chosenMenuIndex = idx;
this.menu(this.chosenMenuIndex); // local function call
console.log('menu index chosen: ', this.chosenMenuIndex);
});
}
menu(index: number) {
// do something
}
}


The template for AnotherComponent is below.



<p>
Menu Index: {{chosenMenuIndex}}
</p>


The chosenMenuIndex value will update when ever a new menu item is chosen. You can take any action inside the subscribe that is necessary with your application.



Why is a shared, or common, service a better option than providing, and injecting another component? It keeps you from tightly coupling components. Any given component should not have any awareness of another component, unless a parent component needs to know about child components.



If you choose to provide a component like you would a service, and inject that component into another component, they are tightly coupled. One component is completely dependent on the other. It may start as one component depending one other component, but can quickly turn into one component depending on another, then another, then another. Next thing you know, you are providing a bunch of components when one service could have taken care of that for you.



Here is a example stackblitz of using a shared service for component communication.






share|improve this answer


























  • Thank you for suggesting a solution. But I want to call the function of the child component and not just share value between the components. You might understand the flow I wanted to achieve from this link(stackoverflow.com/questions/53357001/…)

    – user10648256
    Nov 18 '18 at 6:36











  • In that situation, all you have to do is call the component function inside the menuChoosen$.subscribe. My example is setting a local variable, and doing a console.log, but you can add a function call in there, too. I will update the code in my post to show that.

    – R. Richards
    Nov 18 '18 at 12:05



















1














The short answer is that you can't. Each component is an independent entity and unless one component is contained within another (parent/child relationship), there is no direct mechanism for communication between them.



If you need to build some functionality that can be called by several components, build a service. The service can then be accessed by any component that needs it.



You can even use a service to share data. For example, one component can set some flags into a service and another component can later read those flags from the service.



Another option is to use the router and route to the other component, if that makes sense in your case.



Here is a chart I did awhile back identifying some of the key techniques for communicating between components.



enter image description here






share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53328626%2fangular5-how-to-call-the-function-of-different-component%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    Ideally, in this situation you would not want to provide a component like you would normally provide a service, as the currently accepted answer suggests. You could/should use a shared service. I will suggest a shared service to allow the component to component communication you need.



    First thing you will need is a common service that any component could get injected via the IoC container Angular makes available. It could look something like this:



    import { Injectable } from '@angular/core';
    import { Subject } from 'rxjs';

    @Injectable()
    export class CommonService {
    menuChoosen$ = new Subject<number>();

    constructor() { }
    }


    Since you seem to be using Angular 5, you will need to provide this service from the app module.



    import { NgModule } from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';

    import { AppComponent } from './app.component';
    import { OneComponent } from './one/one.component';
    import { AnotherComponent } from './another/another.component';
    import { CommonService } from './common.service';

    @NgModule({
    imports: [ BrowserModule, FormsModule ],
    declarations: [ AppComponent,
    OneComponent,
    AnotherComponent,
    YetAnotherComponent ],
    providers: [ CommonService ], // HERE
    bootstrap: [ AppComponent ]
    })
    export class AppModule { }


    The CommonService service exposes a menuChoosen$ Subject that any component can subscribe to when it needs to know when a menu item has been chosen. In the component where the menu item is selected, you inject the common service, and call the next function on the Subject when a menu option is selected.



    import { Component, OnInit } from '@angular/core';
    import { CommonService } from '../common.service';

    @Component({
    selector: 'app-one',
    templateUrl: './one.component.html',
    styleUrls: ['./one.component.css']
    })
    export class OneComponent implements OnInit {
    data1 = [{item: 'Menu Item 1 (index 0)'}, {item: 'Menu Item 2 (index 1)'}, {item: 'Menu Item 3 (index 2)'}];
    constructor(private commonService: CommonService) { }

    ngOnInit() { }
    menu(index: number) {
    this.commonService.menuChoosen$.next(index); // next fired here!!
    }
    }


    The template for the OneComponent will look something like this:



    <div *ngFor="let data of data1; let i=index">
    <li (click)="menu(i)">{{data.item}} </li>
    </div>


    When a list item (menu item) is clicked, the index (i) value is sent to the menu function, which in turn calls the next function of the CommonService menuChoosen$ Subject.



    Any other component that subscribes to the menuChoosen$ Subject will then be updated. In this case, the AnotherComponent is a subscriber, and will know about the event. See below.



    import { Component, OnInit } from '@angular/core';
    import { CommonService } from '../common.service';

    @Component({
    selector: 'app-another',
    templateUrl: './another.component.html',
    styleUrls: ['./another.component.css']
    })
    export class AnotherComponent implements OnInit {
    chosenMenuIndex: number;
    constructor(private commonService: CommonService) { }

    ngOnInit() {
    // the subscription starts below
    this.commonService.menuChoosen$.subscribe(idx => {
    this.chosenMenuIndex = idx;
    this.menu(this.chosenMenuIndex); // local function call
    console.log('menu index chosen: ', this.chosenMenuIndex);
    });
    }
    menu(index: number) {
    // do something
    }
    }


    The template for AnotherComponent is below.



    <p>
    Menu Index: {{chosenMenuIndex}}
    </p>


    The chosenMenuIndex value will update when ever a new menu item is chosen. You can take any action inside the subscribe that is necessary with your application.



    Why is a shared, or common, service a better option than providing, and injecting another component? It keeps you from tightly coupling components. Any given component should not have any awareness of another component, unless a parent component needs to know about child components.



    If you choose to provide a component like you would a service, and inject that component into another component, they are tightly coupled. One component is completely dependent on the other. It may start as one component depending one other component, but can quickly turn into one component depending on another, then another, then another. Next thing you know, you are providing a bunch of components when one service could have taken care of that for you.



    Here is a example stackblitz of using a shared service for component communication.






    share|improve this answer


























    • Thank you for suggesting a solution. But I want to call the function of the child component and not just share value between the components. You might understand the flow I wanted to achieve from this link(stackoverflow.com/questions/53357001/…)

      – user10648256
      Nov 18 '18 at 6:36











    • In that situation, all you have to do is call the component function inside the menuChoosen$.subscribe. My example is setting a local variable, and doing a console.log, but you can add a function call in there, too. I will update the code in my post to show that.

      – R. Richards
      Nov 18 '18 at 12:05
















    0














    Ideally, in this situation you would not want to provide a component like you would normally provide a service, as the currently accepted answer suggests. You could/should use a shared service. I will suggest a shared service to allow the component to component communication you need.



    First thing you will need is a common service that any component could get injected via the IoC container Angular makes available. It could look something like this:



    import { Injectable } from '@angular/core';
    import { Subject } from 'rxjs';

    @Injectable()
    export class CommonService {
    menuChoosen$ = new Subject<number>();

    constructor() { }
    }


    Since you seem to be using Angular 5, you will need to provide this service from the app module.



    import { NgModule } from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';

    import { AppComponent } from './app.component';
    import { OneComponent } from './one/one.component';
    import { AnotherComponent } from './another/another.component';
    import { CommonService } from './common.service';

    @NgModule({
    imports: [ BrowserModule, FormsModule ],
    declarations: [ AppComponent,
    OneComponent,
    AnotherComponent,
    YetAnotherComponent ],
    providers: [ CommonService ], // HERE
    bootstrap: [ AppComponent ]
    })
    export class AppModule { }


    The CommonService service exposes a menuChoosen$ Subject that any component can subscribe to when it needs to know when a menu item has been chosen. In the component where the menu item is selected, you inject the common service, and call the next function on the Subject when a menu option is selected.



    import { Component, OnInit } from '@angular/core';
    import { CommonService } from '../common.service';

    @Component({
    selector: 'app-one',
    templateUrl: './one.component.html',
    styleUrls: ['./one.component.css']
    })
    export class OneComponent implements OnInit {
    data1 = [{item: 'Menu Item 1 (index 0)'}, {item: 'Menu Item 2 (index 1)'}, {item: 'Menu Item 3 (index 2)'}];
    constructor(private commonService: CommonService) { }

    ngOnInit() { }
    menu(index: number) {
    this.commonService.menuChoosen$.next(index); // next fired here!!
    }
    }


    The template for the OneComponent will look something like this:



    <div *ngFor="let data of data1; let i=index">
    <li (click)="menu(i)">{{data.item}} </li>
    </div>


    When a list item (menu item) is clicked, the index (i) value is sent to the menu function, which in turn calls the next function of the CommonService menuChoosen$ Subject.



    Any other component that subscribes to the menuChoosen$ Subject will then be updated. In this case, the AnotherComponent is a subscriber, and will know about the event. See below.



    import { Component, OnInit } from '@angular/core';
    import { CommonService } from '../common.service';

    @Component({
    selector: 'app-another',
    templateUrl: './another.component.html',
    styleUrls: ['./another.component.css']
    })
    export class AnotherComponent implements OnInit {
    chosenMenuIndex: number;
    constructor(private commonService: CommonService) { }

    ngOnInit() {
    // the subscription starts below
    this.commonService.menuChoosen$.subscribe(idx => {
    this.chosenMenuIndex = idx;
    this.menu(this.chosenMenuIndex); // local function call
    console.log('menu index chosen: ', this.chosenMenuIndex);
    });
    }
    menu(index: number) {
    // do something
    }
    }


    The template for AnotherComponent is below.



    <p>
    Menu Index: {{chosenMenuIndex}}
    </p>


    The chosenMenuIndex value will update when ever a new menu item is chosen. You can take any action inside the subscribe that is necessary with your application.



    Why is a shared, or common, service a better option than providing, and injecting another component? It keeps you from tightly coupling components. Any given component should not have any awareness of another component, unless a parent component needs to know about child components.



    If you choose to provide a component like you would a service, and inject that component into another component, they are tightly coupled. One component is completely dependent on the other. It may start as one component depending one other component, but can quickly turn into one component depending on another, then another, then another. Next thing you know, you are providing a bunch of components when one service could have taken care of that for you.



    Here is a example stackblitz of using a shared service for component communication.






    share|improve this answer


























    • Thank you for suggesting a solution. But I want to call the function of the child component and not just share value between the components. You might understand the flow I wanted to achieve from this link(stackoverflow.com/questions/53357001/…)

      – user10648256
      Nov 18 '18 at 6:36











    • In that situation, all you have to do is call the component function inside the menuChoosen$.subscribe. My example is setting a local variable, and doing a console.log, but you can add a function call in there, too. I will update the code in my post to show that.

      – R. Richards
      Nov 18 '18 at 12:05














    0












    0








    0







    Ideally, in this situation you would not want to provide a component like you would normally provide a service, as the currently accepted answer suggests. You could/should use a shared service. I will suggest a shared service to allow the component to component communication you need.



    First thing you will need is a common service that any component could get injected via the IoC container Angular makes available. It could look something like this:



    import { Injectable } from '@angular/core';
    import { Subject } from 'rxjs';

    @Injectable()
    export class CommonService {
    menuChoosen$ = new Subject<number>();

    constructor() { }
    }


    Since you seem to be using Angular 5, you will need to provide this service from the app module.



    import { NgModule } from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';

    import { AppComponent } from './app.component';
    import { OneComponent } from './one/one.component';
    import { AnotherComponent } from './another/another.component';
    import { CommonService } from './common.service';

    @NgModule({
    imports: [ BrowserModule, FormsModule ],
    declarations: [ AppComponent,
    OneComponent,
    AnotherComponent,
    YetAnotherComponent ],
    providers: [ CommonService ], // HERE
    bootstrap: [ AppComponent ]
    })
    export class AppModule { }


    The CommonService service exposes a menuChoosen$ Subject that any component can subscribe to when it needs to know when a menu item has been chosen. In the component where the menu item is selected, you inject the common service, and call the next function on the Subject when a menu option is selected.



    import { Component, OnInit } from '@angular/core';
    import { CommonService } from '../common.service';

    @Component({
    selector: 'app-one',
    templateUrl: './one.component.html',
    styleUrls: ['./one.component.css']
    })
    export class OneComponent implements OnInit {
    data1 = [{item: 'Menu Item 1 (index 0)'}, {item: 'Menu Item 2 (index 1)'}, {item: 'Menu Item 3 (index 2)'}];
    constructor(private commonService: CommonService) { }

    ngOnInit() { }
    menu(index: number) {
    this.commonService.menuChoosen$.next(index); // next fired here!!
    }
    }


    The template for the OneComponent will look something like this:



    <div *ngFor="let data of data1; let i=index">
    <li (click)="menu(i)">{{data.item}} </li>
    </div>


    When a list item (menu item) is clicked, the index (i) value is sent to the menu function, which in turn calls the next function of the CommonService menuChoosen$ Subject.



    Any other component that subscribes to the menuChoosen$ Subject will then be updated. In this case, the AnotherComponent is a subscriber, and will know about the event. See below.



    import { Component, OnInit } from '@angular/core';
    import { CommonService } from '../common.service';

    @Component({
    selector: 'app-another',
    templateUrl: './another.component.html',
    styleUrls: ['./another.component.css']
    })
    export class AnotherComponent implements OnInit {
    chosenMenuIndex: number;
    constructor(private commonService: CommonService) { }

    ngOnInit() {
    // the subscription starts below
    this.commonService.menuChoosen$.subscribe(idx => {
    this.chosenMenuIndex = idx;
    this.menu(this.chosenMenuIndex); // local function call
    console.log('menu index chosen: ', this.chosenMenuIndex);
    });
    }
    menu(index: number) {
    // do something
    }
    }


    The template for AnotherComponent is below.



    <p>
    Menu Index: {{chosenMenuIndex}}
    </p>


    The chosenMenuIndex value will update when ever a new menu item is chosen. You can take any action inside the subscribe that is necessary with your application.



    Why is a shared, or common, service a better option than providing, and injecting another component? It keeps you from tightly coupling components. Any given component should not have any awareness of another component, unless a parent component needs to know about child components.



    If you choose to provide a component like you would a service, and inject that component into another component, they are tightly coupled. One component is completely dependent on the other. It may start as one component depending one other component, but can quickly turn into one component depending on another, then another, then another. Next thing you know, you are providing a bunch of components when one service could have taken care of that for you.



    Here is a example stackblitz of using a shared service for component communication.






    share|improve this answer















    Ideally, in this situation you would not want to provide a component like you would normally provide a service, as the currently accepted answer suggests. You could/should use a shared service. I will suggest a shared service to allow the component to component communication you need.



    First thing you will need is a common service that any component could get injected via the IoC container Angular makes available. It could look something like this:



    import { Injectable } from '@angular/core';
    import { Subject } from 'rxjs';

    @Injectable()
    export class CommonService {
    menuChoosen$ = new Subject<number>();

    constructor() { }
    }


    Since you seem to be using Angular 5, you will need to provide this service from the app module.



    import { NgModule } from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';

    import { AppComponent } from './app.component';
    import { OneComponent } from './one/one.component';
    import { AnotherComponent } from './another/another.component';
    import { CommonService } from './common.service';

    @NgModule({
    imports: [ BrowserModule, FormsModule ],
    declarations: [ AppComponent,
    OneComponent,
    AnotherComponent,
    YetAnotherComponent ],
    providers: [ CommonService ], // HERE
    bootstrap: [ AppComponent ]
    })
    export class AppModule { }


    The CommonService service exposes a menuChoosen$ Subject that any component can subscribe to when it needs to know when a menu item has been chosen. In the component where the menu item is selected, you inject the common service, and call the next function on the Subject when a menu option is selected.



    import { Component, OnInit } from '@angular/core';
    import { CommonService } from '../common.service';

    @Component({
    selector: 'app-one',
    templateUrl: './one.component.html',
    styleUrls: ['./one.component.css']
    })
    export class OneComponent implements OnInit {
    data1 = [{item: 'Menu Item 1 (index 0)'}, {item: 'Menu Item 2 (index 1)'}, {item: 'Menu Item 3 (index 2)'}];
    constructor(private commonService: CommonService) { }

    ngOnInit() { }
    menu(index: number) {
    this.commonService.menuChoosen$.next(index); // next fired here!!
    }
    }


    The template for the OneComponent will look something like this:



    <div *ngFor="let data of data1; let i=index">
    <li (click)="menu(i)">{{data.item}} </li>
    </div>


    When a list item (menu item) is clicked, the index (i) value is sent to the menu function, which in turn calls the next function of the CommonService menuChoosen$ Subject.



    Any other component that subscribes to the menuChoosen$ Subject will then be updated. In this case, the AnotherComponent is a subscriber, and will know about the event. See below.



    import { Component, OnInit } from '@angular/core';
    import { CommonService } from '../common.service';

    @Component({
    selector: 'app-another',
    templateUrl: './another.component.html',
    styleUrls: ['./another.component.css']
    })
    export class AnotherComponent implements OnInit {
    chosenMenuIndex: number;
    constructor(private commonService: CommonService) { }

    ngOnInit() {
    // the subscription starts below
    this.commonService.menuChoosen$.subscribe(idx => {
    this.chosenMenuIndex = idx;
    this.menu(this.chosenMenuIndex); // local function call
    console.log('menu index chosen: ', this.chosenMenuIndex);
    });
    }
    menu(index: number) {
    // do something
    }
    }


    The template for AnotherComponent is below.



    <p>
    Menu Index: {{chosenMenuIndex}}
    </p>


    The chosenMenuIndex value will update when ever a new menu item is chosen. You can take any action inside the subscribe that is necessary with your application.



    Why is a shared, or common, service a better option than providing, and injecting another component? It keeps you from tightly coupling components. Any given component should not have any awareness of another component, unless a parent component needs to know about child components.



    If you choose to provide a component like you would a service, and inject that component into another component, they are tightly coupled. One component is completely dependent on the other. It may start as one component depending one other component, but can quickly turn into one component depending on another, then another, then another. Next thing you know, you are providing a bunch of components when one service could have taken care of that for you.



    Here is a example stackblitz of using a shared service for component communication.







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Nov 20 '18 at 15:48

























    answered Nov 16 '18 at 23:43









    R. RichardsR. Richards

    14.1k93642




    14.1k93642













    • Thank you for suggesting a solution. But I want to call the function of the child component and not just share value between the components. You might understand the flow I wanted to achieve from this link(stackoverflow.com/questions/53357001/…)

      – user10648256
      Nov 18 '18 at 6:36











    • In that situation, all you have to do is call the component function inside the menuChoosen$.subscribe. My example is setting a local variable, and doing a console.log, but you can add a function call in there, too. I will update the code in my post to show that.

      – R. Richards
      Nov 18 '18 at 12:05



















    • Thank you for suggesting a solution. But I want to call the function of the child component and not just share value between the components. You might understand the flow I wanted to achieve from this link(stackoverflow.com/questions/53357001/…)

      – user10648256
      Nov 18 '18 at 6:36











    • In that situation, all you have to do is call the component function inside the menuChoosen$.subscribe. My example is setting a local variable, and doing a console.log, but you can add a function call in there, too. I will update the code in my post to show that.

      – R. Richards
      Nov 18 '18 at 12:05

















    Thank you for suggesting a solution. But I want to call the function of the child component and not just share value between the components. You might understand the flow I wanted to achieve from this link(stackoverflow.com/questions/53357001/…)

    – user10648256
    Nov 18 '18 at 6:36





    Thank you for suggesting a solution. But I want to call the function of the child component and not just share value between the components. You might understand the flow I wanted to achieve from this link(stackoverflow.com/questions/53357001/…)

    – user10648256
    Nov 18 '18 at 6:36













    In that situation, all you have to do is call the component function inside the menuChoosen$.subscribe. My example is setting a local variable, and doing a console.log, but you can add a function call in there, too. I will update the code in my post to show that.

    – R. Richards
    Nov 18 '18 at 12:05





    In that situation, all you have to do is call the component function inside the menuChoosen$.subscribe. My example is setting a local variable, and doing a console.log, but you can add a function call in there, too. I will update the code in my post to show that.

    – R. Richards
    Nov 18 '18 at 12:05













    1














    The short answer is that you can't. Each component is an independent entity and unless one component is contained within another (parent/child relationship), there is no direct mechanism for communication between them.



    If you need to build some functionality that can be called by several components, build a service. The service can then be accessed by any component that needs it.



    You can even use a service to share data. For example, one component can set some flags into a service and another component can later read those flags from the service.



    Another option is to use the router and route to the other component, if that makes sense in your case.



    Here is a chart I did awhile back identifying some of the key techniques for communicating between components.



    enter image description here






    share|improve this answer




























      1














      The short answer is that you can't. Each component is an independent entity and unless one component is contained within another (parent/child relationship), there is no direct mechanism for communication between them.



      If you need to build some functionality that can be called by several components, build a service. The service can then be accessed by any component that needs it.



      You can even use a service to share data. For example, one component can set some flags into a service and another component can later read those flags from the service.



      Another option is to use the router and route to the other component, if that makes sense in your case.



      Here is a chart I did awhile back identifying some of the key techniques for communicating between components.



      enter image description here






      share|improve this answer


























        1












        1








        1







        The short answer is that you can't. Each component is an independent entity and unless one component is contained within another (parent/child relationship), there is no direct mechanism for communication between them.



        If you need to build some functionality that can be called by several components, build a service. The service can then be accessed by any component that needs it.



        You can even use a service to share data. For example, one component can set some flags into a service and another component can later read those flags from the service.



        Another option is to use the router and route to the other component, if that makes sense in your case.



        Here is a chart I did awhile back identifying some of the key techniques for communicating between components.



        enter image description here






        share|improve this answer













        The short answer is that you can't. Each component is an independent entity and unless one component is contained within another (parent/child relationship), there is no direct mechanism for communication between them.



        If you need to build some functionality that can be called by several components, build a service. The service can then be accessed by any component that needs it.



        You can even use a service to share data. For example, one component can set some flags into a service and another component can later read those flags from the service.



        Another option is to use the router and route to the other component, if that makes sense in your case.



        Here is a chart I did awhile back identifying some of the key techniques for communicating between components.



        enter image description here







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 16 '18 at 1:39









        DeborahKDeborahK

        26.4k53866




        26.4k53866






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53328626%2fangular5-how-to-call-the-function-of-different-component%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            鏡平學校

            ꓛꓣだゔៀៅຸ໢ທຮ໕໒ ,ໂ'໥໓າ໼ឨឲ៵៭ៈゎゔit''䖳𥁄卿' ☨₤₨こゎもょの;ꜹꟚꞖꞵꟅꞛေၦေɯ,ɨɡ𛃵𛁹ޝ޳ޠ޾,ޤޒޯ޾𫝒𫠁သ𛅤チョ'サノބޘދ𛁐ᶿᶇᶀᶋᶠ㨑㽹⻮ꧬ꧹؍۩وَؠ㇕㇃㇪ ㇦㇋㇋ṜẰᵡᴠ 軌ᵕ搜۳ٰޗޮ޷ސޯ𫖾𫅀ल, ꙭ꙰ꚅꙁꚊꞻꝔ꟠Ꝭㄤﺟޱސꧨꧼ꧴ꧯꧽ꧲ꧯ'⽹⽭⾁⿞⼳⽋២៩ញណើꩯꩤ꩸ꩮᶻᶺᶧᶂ𫳲𫪭𬸄𫵰𬖩𬫣𬊉ၲ𛅬㕦䬺𫝌𫝼,,𫟖𫞽ហៅ஫㆔ాఆఅꙒꚞꙍ,Ꙟ꙱エ ,ポテ,フࢰࢯ𫟠𫞶 𫝤𫟠ﺕﹱﻜﻣ𪵕𪭸𪻆𪾩𫔷ġ,ŧآꞪ꟥,ꞔꝻ♚☹⛵𛀌ꬷꭞȄƁƪƬșƦǙǗdžƝǯǧⱦⱰꓕꓢႋ神 ဴ၀க௭எ௫ឫោ ' េㇷㇴㇼ神ㇸㇲㇽㇴㇼㇻㇸ'ㇸㇿㇸㇹㇰㆣꓚꓤ₡₧ ㄨㄟ㄂ㄖㄎ໗ツڒذ₶।ऩछएोञयूटक़कयँृी,冬'𛅢𛅥ㇱㇵㇶ𥄥𦒽𠣧𠊓𧢖𥞘𩔋цѰㄠſtʯʭɿʆʗʍʩɷɛ,əʏダヵㄐㄘR{gỚṖḺờṠṫảḙḭᴮᵏᴘᵀᵷᵕᴜᴏᵾq﮲ﲿﴽﭙ軌ﰬﶚﶧ﫲Ҝжюїкӈㇴffצּ﬘﭅﬈軌'ffistfflſtffतभफɳɰʊɲʎ𛁱𛁖𛁮𛀉 𛂯𛀞నఋŀŲ 𫟲𫠖𫞺ຆຆ ໹້໕໗ๆทԊꧢꧠ꧰ꓱ⿝⼑ŎḬẃẖỐẅ ,ờỰỈỗﮊDžȩꭏꭎꬻ꭮ꬿꭖꭥꭅ㇭神 ⾈ꓵꓑ⺄㄄ㄪㄙㄅㄇstA۵䞽ॶ𫞑𫝄㇉㇇゜軌𩜛𩳠Jﻺ‚Üမ႕ႌႊၐၸဓၞၞၡ៸wyvtᶎᶪᶹစဎ꣡꣰꣢꣤ٗ؋لㇳㇾㇻㇱ㆐㆔,,㆟Ⱶヤマފ޼ޝަݿݞݠݷݐ',ݘ,ݪݙݵ𬝉𬜁𫝨𫞘くせぉて¼óû×ó£…𛅑הㄙくԗԀ5606神45,神796'𪤻𫞧ꓐ㄁ㄘɥɺꓵꓲ3''7034׉ⱦⱠˆ“𫝋ȍ,ꩲ軌꩷ꩶꩧꩫఞ۔فڱێظペサ神ナᴦᵑ47 9238їﻂ䐊䔉㠸﬎ffiﬣ,לּᴷᴦᵛᵽ,ᴨᵤ ᵸᵥᴗᵈꚏꚉꚟ⻆rtǟƴ𬎎

            Why https connections are so slow when debugging (stepping over) in Java?