Angular 5 shared function & variable among two components

I need a global function for two separate components. I’m loading two angular components using selectors on a main HTML page. One has function buttons and its function has to affect content in the other component as well.

I realized this can’t be easily done… how do you guys set up shared function & variables between two angular components? I’m trying to create a single button which can load tab contents in two separate components. is using angular local storage a solution to store certain function and variables?

Thanks in advance,

1 answer

  • answered 2018-01-11 21:56 Bogdan Bogdanov

    It is pretty simple with service.

    export class ExampleService {
    
       public sharedVariable: any;
    
       public sharedFunction() {
           // your implementation
       }
    }
    
    
    export class Component1 {
        public constructor(private service: ExampleService) {
            this.service.sharedFunction();
            this.service.sharedVariable;
        }
    }
    
    export class Component2 {
        public constructor(private service: ExampleService) {
            this.service.sharedFunction();
            this.service.sharedVariable;
        }
    }
    

    In the case of using a common class, you will get two different references for the sharedVariable and if you change the variable value in the first component it won't affect the second one, but if you use service the service is singleton by default in angular so you will get the same value in both components but changing the value just ones from anywhere.

    export abstract class BaseClass {
    
       public sharedVariable: any;
    
       public sharedFunction() {
           // your implementation
       }
    }
    
    
    export class Component1 extends BaseClass {
        public constructor() {
            super();
            this.sharedFunction();
            this.sharedVariable;
        }
    }
    
    export class Component2 extends BaseClass {
        public constructor() {
            super();
            this.sharedFunction();
            this.sharedVariable;
        }
    }
    

    Hope that helps.