Inter-component communication through service interaction

In order to achieve reusability, I have designed two generic components known as 1)list and 2)details:

Here is a visual representation of the components:

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

Now, these components are being reused in other components named SCHOOL and COLLEGE, which will appear as follows:

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

Currently,

  • When a user clicks on a list-item (e.g. school 1) from the list component within the SCHOOL component, the details of that particular item (e.g. Name, email) should be displayed on the right side (i.e. on the details page/component).

  • Similarly, clicking on a list-item (e.g. college 1) from the list component within the COLLEGE component should result in showing the specific item details (e.g. Name, email) on the right side (i.e. on the details page/component).

I found a solution to this issue through this question. This example involves communication between components using services. However, my challenge lies in reusing the component. How can I implement services when reusing components?

Check out the Stackblitz DEMO

Answer №1

To effectively handle your current situation, it is recommended to utilize the @Input and @Output decorators.

The details component should have an @Input to receive contact details from its parent component.

@Component({
  selector: 'app-details',
  templateUrl: './details.component.html',
  styleUrls: ['./details.component.css']
})
export class DetailsComponent {

  @Input()
  public contact;

}

The list component will emit selected values when any items are chosen from the list.

export class ListComponent {

  @Output()
  public select;

  public onSelect(contact){
     this.select.emit(contact);
  }

}

The school and college components can receive the emitted value from the list component and pass it on to the details component.

<div class="header">
   <h3>SCHOOL</h3>
  <div  class="left">
      <app-list  [contacts]="contacts" ></app-list>
  </div>
    <div  class="right">
      <app-details></app-details>  
    </div>
</div>

View the live example here - https://stackblitz.com/edit/list-examples-mine-ilxisk

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

Leveraging TypeScript to share information between directives in AngularJS through asynchronous calls

Although I've found some scattered information on how to tackle this issue, I haven't been able to find a solid solution. In my AngularJS application, I have an asynchronous call that fetches data from a server and I need to store it in a variab ...

Angular Component Encounters 401 Error Connecting to Youtube API

I've been working on a project in Angular that involves retrieving a list of YouTube videos using the YouTube API. Below is the service I've put together to handle this task. import { Injectable } from '@angular/core'; import { HttpClie ...

Splitting a string in Angular: A step-by-step guide

Is there a way to separate a string using the pipe symbol? The string I have is: Alex Santos||<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0968656c71277a68677d667a479871ab808a88878a">[email protected]</a> I on ...

Unable to break down the property 'desks' of '(0 , _react.useContext)(...)' due to its undefined nature

Trying to mock DeskContext to include desks and checkIfUserPresent when calling useContext is causing an error to occur: Cannot destructure property 'desks' of '(0 , _react.useContext)(...)' as it is undefined TypeError: Cannot destruct ...

Approach to Monitoring Notifications

Is there a best practice for managing notifications in an AngularJS application? When I mention 'notifications', I am referring to alerts that should be displayed to the user while they are logged into the app. My idea is to show the user any u ...

User instance does not function with the binding

When text is entered into the text box, the Angular form value changes but the userModel value remains the same , always displaying [Vino] as the userModel value. Below is the code from app.component.html, <form #userForm="ngForm"> {‌{userFor ...

Effective strategies for efficiently managing a multitude of key codes within an event handler?

This might lean towards a pure JS question, but I'm including Angular2 as well in case any developers with Angular expertise have alternative techniques for this While developing an angular2 application, I'm implementing a keydown event handler ...

Spring Boot + Angular: missing required parameter is causing an issue

When working on my project, I encountered an issue with sending a POST request from the client side in Angular to a server based on Spring Boot. Here is the code snippet I used: const headers = new HttpHeaders().set( "Content-Type", "app ...

Exploring Angular 2's Observable Patterns and Subscribing Techniques

Despite perusing various posts and documentation on the topic, I am still unable to grasp the concept of observables and subscribing to them. My struggle lies in updating an array in one component and displaying it in another component that is not direct ...

Guide on accessing and manipulating local files using an Angular application

For my Angular 7 web app project, I'm looking to allow users to complete surveys and submit their responses. Since I don't have a database set up yet, I thought of storing the results in a local json file for now. Unfortunately, I'm facing d ...

Ensure that all images uploaded are adjusted to fit the consistent dimensions within a card

I am in the process of creating a form that allows users to upload various images, which will then be displayed as cards on a website. After uploading an image, the size of the card automatically adjusts to fit the image, ensuring that all cards maintain ...

Exploring the functionalities of can-deactivate without incorporating routing

I'm facing an issue with a parent component and multiple child components. The parent component contains a form, while each child component also has its own form. Unfortunately, all child components share the same route as the parent component and hav ...

Struggling to reset the first item in an HTML select dropdown with Angular - any tips?

I am having an issue with my dropdown in a modal window. When I first open the modal, the dropdown works as expected. However, if I make a selection and then close and reopen the modal, the selected value remains instead of resetting to 'None selected ...

Unwrapping nested objects in a JSON array with JavaScript: A step-by-step guide

After trying some code to flatten a JSON, I found that it flattened the entire object. However, my specific requirement is to only flatten the position property. Here is the JSON array I am working with: [{ amount:"1 teine med 110 mtr iletau" comment:"" ...

Utilize the express library (NodeJS, TypeScript) to send back the results of my function

I am curious about how I can handle the return values of my functions in my replies. In this specific scenario, I am interested in returning any validator errors in my response if they exist. Take a look at my SqlCompanyRepository.ts: async create(compan ...

Error encountered during the deployment of Ionic 3 with TypeScript

After completing the development of my app, I ran it on ionic serve without any issues. However, when compiling the app, I encountered the following error message. Any assistance in resolving this matter would be greatly appreciated. [15:40:08] typescri ...

How do I go about utilizing or bringing in those constants within the Drawerr.js module?

Currently, working with Next.js, I have defined some constants in the Nav.js file: export default function NestedList() { const [value,setValue]=React.useState(); const theme=useTheme(); const isMatch=useMediaQuery(theme.breakpoints.down('lg&apo ...

The repository's dependencies remain unresolved by Nest

I encountered an error in my nestjs application. Unfortunately, I am having trouble identifying the issue within my code snippet. Here is a glimpse of the relevant sections: AppModule import { Module } from '@nestjs/common'; import { TypeOrmMod ...

What is the process for uploading an array of files with AngularFire2 and Firebase Storage?

I encountered a dilemma trying to find answers to my question. Most resources, like the AngularFire2 documentation and an informative tutorial from angularfirebase.com, only demonstrate uploading one file at a time. As I aim to construct a photo gallery CM ...

Troubleshooting change detection problem in Ionic 3 application

There seems to be an issue with the data not being reflected in the view despite changes in the service and component. Various solutions were attempted to address this issue, but none have proven successful: Utilized the ngDoCheck lifecycle hook Imp ...