Reputation: 33
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?
Upvotes: 3
Views: 17059
Reputation: 60518
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
Upvotes: 4
Reputation: 6325
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
Upvotes: 0
Reputation: 7326
look in environments/environment.ts , you can put your variable there, or you can use like this
export const config = {
variable1: 'ble',
variable2: 'bla'
};
Upvotes: 1