Sending the chosen dropdown ID to a different component

In my application, there is a component named list where I am showcasing all the names of my customers in a dropdown, as illustrated below:

https://i.sstatic.net/KEmAG.png

When a particular item (i.e., customer) is selected from the dropdown, I would like to emit that id to a method/function located in another component known as display.

Code snippet for the display component:

TS file

import { Component, OnInit } from '@angular/core';
import { ContactService } from '../contacts.service';

@Component({
  selector: 'app-display',
  templateUrl: './display.component.html',
  styleUrls: ['./display.component.css']
})
export class DisplayComponent implements OnInit {
public contacts:any;
  constructor(private myService: ContactService) { }

public async ngOnInit(): Promise<void> {
 this.contacts = await this.myService.getCustomersById('id');<=== Need to pass emitted customer id to here
}

}
  • I am currently emitting the ID from the dropdown in the list component.

  • However, I am facing difficulty passing the emitted id to the services file and subscribing to that id in the display component. Although I have created a services file, I am struggling to communicate with it.

DEMO

Answer №1

Modified the click event from (onSelectionChange) to (click).

HTML Code:

<div class="main-div">
<h3>List</h3>
<mat-form-field>
  <mat-select placeholder="Select Customer">
    <mat-option *ngFor="let customer of customers" [value]="customer.id" (click)="selected($event, customer.id)">
      {{customer.customerName}}
    </mat-option>
  </mat-select>
</mat-form-field>
</div> 

TS Code:

public async selected(event: MatOptionSelectionChange, id: string): Promise<void> {
    this.myService.onCustomerSelect.next(id);
}

Service.ts:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { ICustomer } from './models';
import { BehaviorSubject } from 'rxjs';

@Injectable()
export class ContactService {
 private  baseUrl : string = '../../assets/customers.json';

 onCustomerSelect: BehaviorSubject<any> = new BehaviorSubject<any>(null);
  constructor(private http: HttpClient) { }


 public getCustomers(id : string): Promise<ICustomer> {
  const apiUrl: string = '../../assets/customers.json';

  return this.http.get<ICustomer>(apiUrl + id).toPromise();
}

public async getCustomersById(id : string): Promise<ICustomer[]> {
    const apiUrl: string = `${this.baseUrl}/${id}`;

    return this.http.get<ICustomer[]>(apiUrl).toPromise();
  }

}

UPDATED STACKBLITZ

EDIT:

API can be called in the following way:

public async ngOnInit(): Promise<void> {
    this.myService.onCustomerSelect.subscribe(value => {
      console.log('FROM Display Comp -----', value);
      this.CustId = value;
      if (this.CustId) {
        this.myService.getCustomersById(this.CustId).then(response =>{
          console.log(response)
        })
      }
    })
  }

Answer №2

One effective way to share data with components that are not directly related is by utilizing the Subject feature from rxjs. Here's an example to illustrate:

Begin by creating a new instance of Subject in your service:

import { BehaviorSubject } from 'rxjs';
static dataStream: BehaviorSubject<any> = new BehaviorSubject<any>(null);

When you need to send data from a component where the information originates, simply call this method (Assuming our service is named DataService):

DataService.dataStream.next(newValue);

To receive and access this data in a different component, subscribe to the Subject within the ngOnInit lifecycle hook. This ensures that whenever new data is sent through the same Subject instance, it will be received by all active subscriptions:

DataService.dataStream.subscribe(data => {
      console.log('Received data: ', data);
});

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

What is the correct way to assign multiple types to a single entity in TypeScript?

(code at the end) While attempting to write section.full.link, I encountered the following error: Property 'link' does not exist on type 'SectionSingle | SectionTitle | SectionHeaderMedia'. Property 'link' does not exist on ...

Obtain the selected option's value using Angular

Having an issue with my user.model.ts file. I have a list of users that I can edit by clicking on a button that filters the user's data and puts it in a bootstrap modal. I'm using [ngModel] in a select tag to get the country of my user, but when ...

Inserting a pause between a trio of separate phrases

I am dealing with three string variables that are stacked on top of each other without any spacing. Is there a way to add something similar to a tag in the ts file instead of the template? Alternatively, can I input multiple values into my angular compo ...

"Troubangular: Troubleshooting unexpected behavior when trying to update ngFor after setting a property

Dealing with what seems like a straightforward component here. I'm fetching an array of objects from an API, storing them in a property, and then displaying them in a select list for the user to choose from. When the value changes, I filter the result ...

Tips for implementing a hover effect across the entire line in a line chart using Chart.js

initializeChart(): void { var myGraph = new Chart('myGraph', { type: 'bar', data: { labels: ['Modes'], datasets: [ { label: 'A', data: [this.data.a], borderColor: ' ...

Ways to keep information hidden from users until they actively search for it

Currently, I have a custom filter search box that is functioning correctly. However, I want to modify it so that the data is hidden from the user until they perform a search. Can you provide any suggestions on how to achieve this? Below is the code I am u ...

Angular Material Textbox with drop shadow

Currently working on a form design and aiming for the input box to resemble the image provided within the angular material matInput framework. Any suggestions on how to accomplish this? Attached is a visual representation of the desired input box appearan ...

Checking the functionality of a feature with Jasmine framework in an Angular application

I am working on writing unit test cases and achieving code coverage for the code snippet below. Any advice on how to proceed? itemClick($event: any) { for (let obj of this.tocFiles) { let results = this.getchildren(obj, label); if (results) { conso ...

Passing a service into a promise in Angular 2 using TypeScript

Is there a way to pass a service into a promise? I am currently working on a promise that will only resolve once all the http requests are complete. However, I am facing an issue where this.jiraService is undefined. Is there a method to pass it to the co ...

How can I reduce unnecessary spacing in a primeNg Dropdown (p-dropdown) filter within an Angular 5 application?

In my Angular 5 project, I have implemented PrimeNG dropdown (p-dropdown) and encountered an issue. When I try to filter the dropdown data by adding spaces before and after the search term, it displays a No Results Found message. How can I fix this problem ...

Convert TypeScript model to JSON while excluding properties with null values

When working with an Angular 4 App and a typescript model, I have defined a Person class as follows: export class Person{ fname:string, lname?:string } The 'lname' property in the model is optional. To populate the model in a component, I u ...

Enhancing a component with injected props by including type definitions in a higher-order component

Implementing a "higher order component" without types can be achieved as shown below: const Themeable = (mapThemeToProps) => { return (WrappedComponent) => { const themedComponent = (props, { theme: appTheme }) => { return <Wrapped ...

Error Encountered While Building AWS Amplify with Ionic 5 and Angular 10

Our team is currently facing a challenge at my company that we've been struggling to resolve, and I was hoping someone here could offer some assistance. We are using AWS Amplify in our Angular 10/Ionic 5 project, and encountering the following error: ...

encountering the issue of not being able to assign a parameter of type 'string | undefined' to a parameter of type

Seeking help with the following issue: "Argument of type 'string | undefined' is not assignable to parameter of type" I am unsure how to resolve this error. Here is the section of code where it occurs: export interface IDropDown { l ...

The value produced by the interval in Angular is not being displayed in the browser using double curly braces

I am attempting to display the changing value on the web page every second, but for some reason {{}} is not functioning correctly. However, when I use console.log, it does show the changing value. Here is an excerpt from my .ts code: randomValue: number; ...

The CSS scale property is not working as expected when used in a React.js application, specifically

working environment ・next.js ・react ・typescript https://www.youtube.com/watch?v=ujlpzTyJp-M A Toolchip was developed based on the referenced video. However, the --scale: 1; property is not being applied. import React, { FunctionComponent ...

Storing and Retrieving User Identifiers in Next.js

Currently, I am developing a project using Next.js and I have the requirement to securely store the userId once a user logs in. This unique identifier is crucial for accessing personalized user data and creating dynamic URLs for the user profile menu. The ...

Is it necessary to include async/await in a method if there is already an await keyword where it is invoked?

Here are the two methods I have written in Typescript: async getCertURL(pol: string): Promise<string> { return await Api.getData(this.apiUrl + pol + this.certEndpoint, {timeout: 60000}).then( (response) => { return response.data.certUR ...

Deserializing concrete types from an abstract list in TypeScript (serialized in JSON.NET)

I'm working with an API that returns an object containing a list of various concrete types that share a common base. Is there a way to automate the process of mapping these items to a specific Typescript interface model-type without having to manually ...

The global class variable encounters an error when trying to assign the value of "socket" to it

Within my class constructor, I am setting up a Socket connection and then storing the socket parameter in a global class variable (this.socket_variable = socket) so that I can access it across all functions in the class. CODE const { Server } = require(&q ...