Home > Net >  Simplest way to share a variable between angular components
Simplest way to share a variable between angular components

Time:11-07

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

  1. @Input, @ViewChild - this kind of communication is used when components are parent-child in an HTML template
  2. @Injectable (services, tokens) - use this when components are located in different trees
  3. 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());
  }

}

  • Related