Jlee Jlee - 1 year ago 1387
AngularJS Question

Angular 2/Ionic 2 ngModel Dynamic Global Variable

Hi everyone I currently am attempting to use my ngModeled variable globally.

So far I have the following code snippet.


<ion-input type="text" value="" [(ngModel)]="databaseID">


public databaseID;

These functions work and when I attempt to print the ngModeled data from the home.ts class it prints what has been entered by the user. However I am not sure how to call databaseID from another class. I have tried setting databaseID to global (globals are static and therefor this will not work).

Could you possibly explain a way that I may access this variable from a different class?

Some possible thoughts I had were dependency injection and using a providers. But I'm not sure what would be the best way to do so.

Answer Source

The best way to share a variable between different components/directives is to use a service. What you can do is bind the ngModel directly to a service, and then access the service from multiple components.


export class MyService {
    databaseId: string;

    constructor() {
        this.databaseId = "1234";


export class MyComponent {
    constructor(private myService: MyService) { }


<ion-input type="text" value="" [(ngModel)]="myService.databaseID">

Services Tutorial: https://angular.io/docs/ts/latest/tutorial/toh-pt4.html

Dependency Injection: https://angular.io/docs/ts/latest/cookbook/dependency-injection.html

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download