简体   繁体   中英

Angular 5 share variable between two components

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM