0

I have 2 components. Component A and B. Component B has a value that I am trying to rereive in component A. Component B lies in a different folder to A. How can I send the value to A without using something like localStorage.

Here is my code for context.

Compononent B

@Input() offerExpiry: any;

  async ngOnInit() {
    this._loader.start();
    if (this._exploreService.offer) {
        ...
    } else {
      const offer = await this._exploreService.getOfferDetails();
      //value I need is 'this.offerExpiry'
      this.offerExpiry = offer.expiryDate;
    }
    this._loader.stop();
  }

Compononent A

import { Component, Input, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'app-offer-subheader',
  templateUrl: './offer-subheader.component.html',
  styleUrls: ['./offer-subheader.component.scss']
})
export class OfferSubheaderComponent {

  @Input() title: string;
  @Input() active: string;
  @Output() back = new EventEmitter();
  @Output() offerExpiry: any;

  onBack() {
    this.back.emit();
  }

}

I am trying to use Input, Output but am not having any success

skydev
  • 1,867
  • 9
  • 37
  • 71
  • 1
    check this (possible duplicate): https://stackoverflow.com/q/30501577/2050306 – robert May 29 '19 at 11:37
  • Yes thanks, my one is duplicated. Will close. – skydev May 29 '19 at 11:50
  • Possible duplicate of [How to communicate between component in Angular?](https://stackoverflow.com/questions/30501577/how-to-communicate-between-component-in-angular) – skydev May 29 '19 at 11:51
  • you can check this https://stackblitz.com/edit/angular-ydxhki - as of now im passing true from child to parrent. use the service if both are in same level(not parent and child). – Muthu R May 29 '19 at 12:05

1 Answers1

1

You can solve it in 2 ways:

  1. You need create more one Parent component or using your app component, component B has @Output() and component A @Input(). You subscribe to component B @Output changes and set value to Parent component, and pass it on input of your component A.
  2. Create a service like this:

    export class ExchangeService { private value$: BehaviorSubject = new BehaviorSubject(1);

      get value() {
        return this.value$.asObservable();
      }
    
      updateValue(value: number) {
        this.value$.next(value);
      }
    }
    

And inject it in both your components and enjoy your data managing)

Dmitry Sobolevsky
  • 1,171
  • 6
  • 12