How to pass variable value from one component to another in Angular2
I am rebuilding an old web framework (coded in php) using Angular4 and angular-cli.
I'm looking for a way to declare multiple variables once in a component named my-configuration so that I can use them directly in other components like my-footer without reusing 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?
source to share
The recommended way to exchange data throughout the application is to use an Angular service. They are defined as single values, so whatever values ββyou save are available to the entire application.
You can find out more about the services here: https://angular.io/docs/ts/latest/tutorial/toh-pt4.html
I just put together a blog post and plunker showing how to do this:
http://blogs.msmvps.com/deborahk/build-a-simple-angular-service-to-share-data/
enter code here
source to share
if your two components have parent and child relationship you can use @ViewChild () or @Output (), otherwise Service is the best way to share data.
you can find more information on component communication https://angular.io/docs/ts/latest/cookbook/component-communication.html
source to share