I have a button which suppose to change a boolean variable from true to false and vice versa, like a switch. the variable and the button are in different components, how is that possible to share the variable if they components are not parent-child?
CodePudding user response:
So basically, there are three kinds of sharing data between components
- @Input, @ViewChild - this kind of communication is used when components are parent-child in an HTML template
- @Injectable (services, tokens) - use this when components are located in different trees
- Routing data - that's data available via Router, usually used when the component is placed in router-outlet
CodePudding user response:
You need to use a service. This is outlined here: https://angular.io/guide/component-interaction
You can use a Subject
(no starting value) or a BehviorSubject
(has a starting value) to hold the data, and another property to expose the value as an Observable
that components can subscribe to.
Example:
import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class YourServiceClass {
private _yourValue = new BehaviorSubject<boolean>(false);
yourValue$: Observable<boolean>;
constructor() {
this.yourValue$ = this._yourValue.asObservable();
}
toggleYourValue(): void {
this._yourValue.next(!this._yourValue.getValue());
}
}