-1

I am building an Angular 2 based app. I want to have a global variable that can be accessed and also modified by all components. All current answers I am able to find are for constants. Can anyone suggest how I can do so ? Thanks!

AP01
  • 47
  • 1
  • 2
  • 9

1 Answers1

1

When I have to deal with global variable I usually do it via shared services. I declare a variable in root component's service, which is usually app.service.ts and make it available to other components via setter and getter functions.

To demonstrate, I used a heroes tutorial plunker that has three components. In the app.service.ts I declared a variable myGlobalVar.

I added buttons in all other components to change the value of myGlobalVar and lookup it's value at anytime.

You can find interaction details from this example

app.service.ts:

@Injectable()
export class AppService{
    myGlobalVar;

    constructor(){
      this.myGlobalVar = true;
      console.log("My global variable value: " + this.myGlobalVar);
      alert("My intial global variable value is: " + this.myGlobalVar);
    }

    setMyGV(val: boolean){
      console.log("Setting FV to: " + val);
      this.myGlobalVar = val;
    }

    getMyGV(val: boolean){
      return this.myGlobalVar;
    }
}

Accessing and modifying the variable from a component:

export class exampleComponent{
  constructor(private appService: AppService) {}

  changeGV(val){
      this.appService.setMyGV(val);
    }

    showGV(){
      alert("GV: " + this.appService.getMyGV());
    }
}
Nehal
  • 13,130
  • 4
  • 43
  • 59