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?
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());
}
}
Then in your component(s) you would inject the service and set up a subscription to populate a property on your component, which can be used elsewhere in your code or bound to the template...
@Component({
selector: 'app-your-component',
template: `Your value is: {{ yourValue }}`
})
export class YourComponent implements OnInit, OnDestroy {
subscription: Subscription;
yourValue: boolean;
constructor(
private readonly yourServiceClass: YourServiceClass,
) {}
ngOnInit(): void {
this.subscription =
this.yourServiceClass.yourValue$.subscribe(yourValue => {
this.yourValue = yourValue;
});
}
ngOnDestroy(): void {
this.subscription.unsubscribe();
}
}