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?
-
2angular.io/docs/ts/latest/cookbook/component-communication.htmlsilentsod– silentsod2017-02-07 18:42:49 +00:00Commented Feb 7, 2017 at 18:42
-
You can write a get method for value in one component use it in another componentyala ramesh– yala ramesh2017-02-07 18:44:01 +00:00Commented Feb 7, 2017 at 18:44
-
Isn't it using the child component html template in the master component in this example? As I said I just need a variable value.Ayane– Ayane2017-02-07 18:45:54 +00:00Commented Feb 7, 2017 at 18:45
-
@yala ramesh I think that's exactly what i need could you post a small example of how you get the value?Ayane– Ayane2017-02-07 18:48:36 +00:00Commented Feb 7, 2017 at 18:48
4 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:

3 Comments
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();
}
5 Comments
I was developing a thing and I faced the same challenge. My approach.
I had two different components and a service.
loginComponent, headerCompnent and a loginauth service.
validateUser(name,pass){
this.loginStatus = this.loginauth.validateUser(name,pass);
if(this.loginStatus) this.route.navigate(['/welcome']);
else this.route.navigate(['/login']);
}
I wanted to use "loginStatus" in headerComponent.
this.loginauth.validateUser(name,pass); loginauth was the service and validateUser(...) method inside it.
So I created a static variable inside the service and inject that service into both components and by injecting the same service in headerComponent I was able to retrieve the value of that static variable.
In service, create and initialize it as per your requirement.
static loginFlag = false;
In header component.
Import that service and access that static variable with class name.
LoginAuthService.loginFlag
Comments
You can use constructor.
E.g. I want to use "message" variable of parent component in a child component.
export class ParentComponent {
message: string;
constructor(){
this.message = "Hello"
}
}
below child component you should import the class belongs to parent component. And call it in the child component.
import { ParentComponent } from 'src/app/app.parentcomponent';
export class ChildComponent implements OnInit {
message2 = new ParentComponent;
message3 = this.message2.message;
constructor() { }
ngOnInit(): void {
}
}
At the end message3 equals to "Hello".