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?

+3


source to share


3 answers


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

      

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

+3


source


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



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

      

+1


source


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

0


source







All Articles