Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a variable from a component in another in Angular2

I was wondering if it is possible to use variable values from one component into another one without having to use the template of the first one, just need the value of the variable nothing else. Is it possible?

like image 511
Ayane Avatar asked Feb 07 '17 18:02

Ayane


People also ask

How do you pass variables from one component to another?

For passing the data from the child component to the parent component, we have to create a callback function in the parent component and then pass the callback function to the child component as a prop. This callback function will retrieve the data from the child component.

How import variable from another component react?

To import a variable from another file in React:Export the variable from file A , e.g. export const str = 'hello world' . Import the variable in file B as import {str} from './another-file' .

How do you access the template reference variable in another component?

To get started using template reference variables, simply create a new Angular component or visit an existing one. To create a template reference variable, locate the HTML element that you want to reference and then tag it like so: #myVarName .


2 Answers

Go to your app.module.ts and make the provider of that component you want to inherit with other classes:

Then go to the class you want access of that variable, and import the component into that:

Make the constructor of it:

And happily get access to the variables:

like image 144
Muhammad Awais Avatar answered Oct 20 '22 03:10

Muhammad Awais


Yes possible, you can use the @Input() method or use write get method like below

export class Demo {
    const sum = 10;

    get SumValue() {
        return this.sum;
    }
}

import-->Demo

export class Demo2 {
   private sum: number;
   this.sum = Demo.SumValue();
}
like image 26
yala ramesh Avatar answered Oct 20 '22 05:10

yala ramesh