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

梦想与她 提交于 2019-12-22 04:57:18

问题


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?


回答1:


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();
}



回答2:


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:



来源:https://stackoverflow.com/questions/42097480/how-to-use-a-variable-from-a-component-in-another-in-angular2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!