Angular2 Simple Global Variable Service

ng2-simple-global

A simple global variable service for Angular 2.

Index

Install

npm install ng2-simple-global  

Usage

Import into Angular 2 application (typescript)

ng2-simple-global is implemented as Angular 2 injectable service name SimpleGlobal.

For module using SimpleGlobal

Add SimpleGlobal into module providers.

import { SimpleGlobal } from 'ng2-simple-global';

@NgModule({
    providers: [SimpleGlobal]
})

For each child component using SimpleGlobal

import {SimpleGlobal} from 'ng2-simple-global';

export class ChildComponent {

    constructor(private sg: SimpleGlobal) { }

}

API

import {SimpleGlobal} from 'ng2-simple-global';

@Component({
    selector: 'child-com',
    template: `
        <p>This is a global variable: {{sg.gv}}</p>
        <input type="text" [(ngModel)]="sg.gv">
    `
})
export class ChildComponent {

    localVar;

    constructor(private sg: SimpleGlobal) {
        if (this.sg['gv']) {
            this.localVar = this.sg['gv'];
        }
    }

}

Treat SimpleGlobal instance as a global object and create/assign additional attributes freely,
and it will be accessible to all component using the service.

Repository

ng2-simple-global

Example

ng2-simple-global-example

plunker