0

Im trying to pass variables between two components - they are not parent/child components. I have a file named input.ts with a input.html file where the user types in their input. The values he/she inputs are then pushed into an array inside the input.ts file. I want to be able to access this variable (with pushed values) in another component (calendar.ts and calendar.html), as that is the place where I need to manipulate and push the values into the calendar. I've read that you can use services but it seems rather complicated. Is there a simple way to do this in angular/typescript?

I've tried doing it like below, but with no success unfortunately.

I hope someone could please help me.

Many thanks, and much appreciated!

class InputComponent {
inputtedValuesArray: string[] = []

}

import {InputComponent} from '../input/input.component'
class CalendarComponent {

generateCalendar() { //function just to see the values inside.
for (let i of inputtedValuesArray) {
console.log(i);
}

}
  • 3
    Using a service probably is the simplest way to do this to be honest – user184994 Jan 20 '18 at 14:56
  • use a service to create a global event bus so that you can broadcast your message and subscribe to it as an observable from other component. – Niladri Jan 20 '18 at 15:13
  • Possible duplicate of [Angular2 How to pass selected value to other component](https://stackoverflow.com/questions/43107405/angular2-how-to-pass-selected-value-to-other-component) – Sajeetharan Jan 20 '18 at 17:39

2 Answers2

0

Use Services, this is the best way that can solve your problem

Rohit.007
  • 3,414
  • 2
  • 21
  • 33
0

Thank you to those that answered! Those that are facing the same problem, I created a service.

export class InputService {

public array = [];

getSubjects() {
return this.array.slice();
}

addInputToService (input // eg. an object) {
this.array.push(input);

}

}

I then executed the addInputToService function inside my input component ts file. That way the values are assigned to the array. Another component can then access this array by executing the getSubjects function. This way the contents of the array within the service are put into the array inside the component you need to have the values in.