Passing objects between unrelated components in Angular 2

I am looking for a way to transmit data to another component from a Component that is neither a direct child nor parent.

To better explain my question, I have put together a Plunker example.

When the code snippet below is triggered, I need some mechanism in place to capture it.

 fillSelectT(item){
  //populate Select to
}

The following piece of code should be able to receive and process the transmitted data.

  listener(item){
    selectedItems.push(item);
  }

It's akin to an EventAggregator concept found in C#, which I am attempting to emulate here.

Answer №1

According to the documentation provided here, it is recommended to utilize a shared service between two components. Emit events from the service when selecting an item, and then listen for the emitted events from the other component.

@Injectable()
class SelectionService {
  selections = new Subject<any>
  select(item) {
    this.selections.next(item);
  }
}

Your plunkr has been modified: http://plnkr.co/edit/qJ8bh7wN9qQvKTLJOb0T?p=preview

Answer №2

I have implemented a fully functional example based on your code.

1) Both components are nested within the AppComponent. Create variables and events to handle and store the selected items:

selectedItems: any[] = [];

onSelectItem(item) {
   this.selectedItems.push(item);
}

<select-from (onSelectItem)="onSelectItem($event)"></select-from>
<select-to [selectedItems]="selectedItems"></select-to> 

2) Update the select-from component to emit an event:

@Output() onSelectItem = new EventEmitter<any>();

 fillSelectT(item){
      this.onSelectItem.emit(item);
 }

3) Modify the select-to component to accept a list from its parent component:

@Input() selectedItems:any = [];

Check out the changes made here: Plunker Link

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible for TypeScript to automatically determine the type of an imported module based on its path?

I'm currently working on creating a function, test.isolated(), which wraps around jest.isolateModules. This function takes an array of strings representing the modules to be imported, along with the usual arguments (name, fn, timeout), and then inject ...

Angular - Issue: Attempting to access properties on undefined (specifically 'forEach')

I'm attempting to access the roles array from this object but encountering the following error: TypeError: Cannot read properties of undefined (reading 'forEach') Here is the code snippet causing the issue: this.data.roles.forEach(role =&g ...

Building a personalized action bar with versatile features using React and TypeScript: A step-by-step guide

Is there a more efficient way to create a custom action bar in React using TypeScript? I have implemented it with props for flexible actions, but as the number of actions grows, adding more booleans might become confusing. type CustomBarProps = { with ...

In React Router v6, you can now include a custom parameter in createBrowserRouter

Hey there! I'm currently diving into react router v6 and struggling to add custom params in the route object. Unfortunately, I haven't been able to find any examples of how to do it. const AdminRoutes: FunctionComponent = () => { const ...

How to Generate a JPG File from a Leaflet Map in Angular 4 using Typescript

I am developing a custom application using Angular4 that involves integrating leaflet maps. One of the requirements is to export the current view of a map as a JPG image, capturing only the map with markers and polylines - similar to taking a screenshot. ...

Angular's ng-model is unable to access the value of an object array

When selecting the days, users should be able to input check-in and check-out time ranges dynamically. However, there seems to be an issue with retrieving the values and data format. The ng model is unable to capture the check-in and check-out values. The ...

The type 'false' cannot be assigned to the type 'EventEmitter<any>'

Trying to send a boolean value to the Parent Component is causing an error with the message "Type 'false' is not assignable to type 'EventEmitter'." This is the code snippet: @Output() isTimeBoundAccessEnabled = new EventEmitter(); T ...

Tips for updating the 'value' attribute content in Playwright for Angular version 15

I am seeking guidance on how to access and modify the content of the value attribute in the provided code snippet. <table> <thead> <tr>...</tr> </thead> <tbody> <tr>...</tr> ...

What is the most effective method for obtaining the ViewContainerRef of a mat-row in Angular 4

I am currently working with a mat-table and I'm looking to retrieve the ViewContainerRef of a clicked row in order to add another component within that specific row. Can anyone suggest the most effective method to obtain the ViewContainerRef of a row? ...

Does anyone have experience using the useRef hook in React?

Can someone help me with this recurring issue: "Property 'value' does not exist on type 'never'" interface InputProps { name: string; icon?: ReactElement; placeholder?: string; } const Input = ({ name, icon: Icon, ...rest }: Inpu ...

Axios Error: Header content contains an invalid character ['adapter']

Here is a code snippet that highlights the problem: import axios, { AxiosRequestConfig } from "axios"; function combineRequestParams(defaultParams: AxiosRequestConfig, params1: AxiosRequestConfig, params2?: AxiosRequestConfig): AxiosRequestConfi ...

The Typescript compiler is throwing an error in a JavaScript file, stating that "type aliases can only be used in a .ts file."

After transitioning a react js project to react js with typescript, I made sure to move all the code to the typescript react app and added types for every necessary library. In this process, I encountered an issue with a file called HeatLayer.js, which is ...

The challenge with handling dates in PrimeNG datatable on Angular

I need to include the date in each column of my datatable. The date is received through json and appears as follows: JSON Date 1504836960000 Currently, I am formatting it using piping and ng-template: <ng-template pTemplate="body" let-order="rowData ...

Using NodeJS to retrieve data from Firestore and then transmitting it to a Google Spreadsheet

I've been comparing data from a spreadsheet with a firebase collection to find matching values and retrieve an answer. Now, I need help on how to transfer this answer to another Google spreadsheet. Although I've attempted the method below, I&apo ...

Typescript function incorrectly returns Protractor's "element.all" output as Promise<string> instead of Promise<string[]>

Kindly review the code snippet provided below. The function getAllGroupIds() is designed to return an array of IDs belonging to "group" elements. The goal is to retrieve all the group-ids both before and after a test action, in order to compare them. Howe ...

Encountering the error "TypeError: Unable to access property 'controls' of undefined" when utilizing formArray in Reactive forms

Hi there, I am currently working on creating a dynamic form using formArray in Angular. However, I have run into an issue with the error message "TypeError: Cannot read property 'controls' of undefined." import { Component, OnInit } from ' ...

How can I access properties of generic types in TypeScript?

Converting the generic type to any is a valid approach (The type E could be a typescript type, class, or interface) of various entities like Product, Post, Todo, Customer, etc.: function test<E>(o:E):string { return (o as any)['property' ...

The specified type '(Person | undefined)[]' cannot be assigned to the type 'People'

Encountering a typescript error while trying to update the state from the reducer: The error states: Type '(Person | undefined)[]' is not assignable to type 'People' reducer.ts: export type Person = { id: string; name: string; ph ...

Angular displaying a slice of the data array

After following the example mentioned here, and successfully receiving API data, I am facing an issue where only one field from the data array is displayed in the TypeScript component's HTML element. Below is the content of todo.component.ts file im ...

Incorporating TypeScript into a project that already contains .js files

I currently have a NodeJS project with .js files written in ES6. I am interested in integrating typescript into this existing project. What steps should I follow? Can I simply introduce .ts files within the same directory structure? One issue I have encou ...