1

I have a shared variable I want to declare in both component and I want the components to have shared values. I was wondering if this can be done.

A.html

...
<button (click)="sendInfo(a,b,c)" > </button>
...

B.html

...
<div *ngIf="showData" > {{loadData()}} </div> 
...

A.component.ts

...
showData = false;
sendInfo(a: string, b:string, c:string) {
//calling webservice
showData = true;
}
...

B.component.ts

...
showData = false;
//when button from A.html clicked
showData = true;

So in B.component.ts I want to set the showData to true if the button from A.html is clicked.

  1. How does B.component.ts know when A.component.ts has been changed?

  2. How do I set this shared variable between two component?

2
  • You can use an EventEmitter to notify one component when the other fires the click event. But that assumes your components are in a parent-child Commented Sep 14, 2018 at 19:32
  • the components are sibiling, app.component contains both of those compoents and htmls Commented Sep 14, 2018 at 19:33

1 Answer 1

3

If you want to share a variable between two components use a service and observable using ReplaySubject:

export class Service {
   sharedVariable$ = new ReplaySubject(1);
   updateValue(value) {
       this.sharedVariable$.next(value);
   }
}

In components inject the service:

class Component {
   constructor(public service: Service) {}
}

And use in html:

<span>{{service.sharedVariable$ | async}}</span>
<button (click)="service.updateValue(55)">set 55</button>

This is much better than to share variable using component bindings and future proof.

Sign up to request clarification or add additional context in comments.

3 Comments

but this create infinite loop calls. I want just to check the data once when the button is clicked.
So in B.html {{ service.sharedVariable$ }} would keep printing the same value repeatedly.
there are no infinite calls. You should never call a function in a template. This is observables pattern and it prints out the last value emitted by observable.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.