问题
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