3

I am rebuilding an old web platform (coded in php) using Angular4 and angular-cli.

I'm looking for a way to declare multiple variables once in a component called my-configuration so that I can use them directly in other components, such as my-footer, without redeclaring them:

my-configuration.component.ts

import {Component} from '@angular/core';

@Component ({
  selector: 'my-configuration',
  templateUrl: './my-configuration.component.html',
  styleUrls: ['./my-configuration.component.css']
})

export class MyConfigurationComponent {
    variable1: String;
    variable2: String;

    constructor(){
        this.variable1 = 'value1';
        this.variable2 = 'value2';
    }
}

my-footer.component.ts

import {Component} from '@angular/core';

@Component ({
  selector: 'my-footer',
  templateUrl: './my-footer.component.html',
  styleUrls: ['./my-footer.component.css']
})

export class MyFooterComponent {
    footer-variable1: String;
    footer-variable2: String;

    constructor(){
        this.footer-variable1 = //Get the variable1 value from MyConfigurationComponent;
        this.footer-variable1 = //Get the variable2 value from MyConfigurationComponent;
    }
}

What is the correct method to do so?

3 Answers 3

4

The recommended way to share data throughout an application is to use an Angular service. They are defined as singletons, so any values you retain there are available to the entire application.

You can find out more about services here: https://angular.io/docs/ts/latest/tutorial/toh-pt4.html

I just put together a blog post and a plunker showing how to do this:

http://blogs.msmvps.com/deborahk/build-a-simple-angular-service-to-share-data/

enter code here

https://plnkr.co/edit/KT4JLmpcwGBM2xdZQeI9?p=preview

Sign up to request clarification or add additional context in comments.

Comments

1

look in environments/environment.ts , you can put your variable there, or you can use like this

 export const config = {
  variable1: 'ble',
  variable2: 'bla'
};

1 Comment

You should probably freeze that object to make the properties immutable as well.
0

if your two component have parent and child relation ship you can use @ViewChild() or @Output() otherwise Service is the best way to share the data.

you can find more information about component communication https://angular.io/docs/ts/latest/cookbook/component-communication.html

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.