retrieve information from Angular service

Is there a way for parent components to communicate with child components by injecting providers directly into the TypeScript file of each child component? I am trying to retrieve data using get and set methods, but I am unsure how to proceed. Any suggestions?

Service

export class ProductSharingDataService {

  public productName!: any;

  constructor() { }

  setRowName(selectedTableRowData: any){
    this.productName = selectedTableRowData;
  }

  getRowName(): string {
    return this.productName;
  }

}

components.ts

@Component({
          selector: 'app-product-page',
          templateUrl: './product-page.component.html',
          styleUrls: ['./product-page.component.css'],
          providers: [ProductSharingDataService] // Service injected here
        })
        export class ProductPageComponent {
        
          public selectedArrayParent!: Product;
        
          constructor(private productSharingDataService: 
                      ProductSharingDataService) {
            this.productSharingDataService.getRowName();  
            }
        
          receive($event: any) {
            this.selectedArrayParent = $event; 
// Trying to extract data from $event
          }
        
        }

Answer №1

There are a variety of methods to facilitate communication between a component parent and child:

NOTE: It is essential to specify the appropriate type instead of using 'any'.

1) Utilizing a service as a 'store':

service https://angular.io/guide/component-interaction#parent-and-children-communicate-using-a-service

export class ProductSharingDataService {

  private _productName!:any;

  set rowName(selectedTableRowData:any){
    this._productName = selectedTableRowData;
  }

  get rowName():string{
    return this._productName;
  }

  constructor() { }

}

parent

  constructor(private productSharingDataService: ProductSharingDataService) {
     this.productSharingDataService.rowName = 'Info (object, string, whatever...) you want to pass to the child';  
  }

child

name: any;

  constructor(private productSharingDataService: ProductSharingDataService) {
     this.name = this.productSharingDataService.rowName;
  }

2) Implementing @input() and @output: https://angular.io/guide/component-interaction

- Within the child component:

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


 @Component({
      selector: 'app-child', ....



   @Input() varNameIn: any[] = []; 
    @Output() varNameOut: EventEmitter<any> 
      = new EventEmitter();
    ...

To send data to the parent component:

const infoToParent:any = 'Info (object, string, whatever...) you want to pass to the parent';
this.varNameOut.emit(info);

- Within the parent component:

HTML:

...
<app-child [varNameIn]="infoToChild" (varNameOut)="parentMethodToUseVarNameOutContent($event)"></app-child>
....

TypeScript:

    ...

    // Specify the same type for varNameOut as in the child:
    ...
    const infoToChild="Info (object, string, whatever...) you want to pass to the child";
    ...
    parentMethodToUseVarNameOutContent(varNameOut: any){
       console.log(varNameOut);
    }
    ...

Answer №2

Utilizing the @input() and @output decorator permits transferring data between components. The usage of the @output decorator in this method could potentially resolve your issue.

Within the recipient component (referred to as ProductPageParentComponent) TypeScript file, you must create a function to accept the value of the productName variable:

export class ProductPageParentComponent{

constructor() { }

productName: string;

receiveStringValue($event) {
  this.productName= $event;
 }
}

In the recipient component's HTML, include the following code:

<app-product-child-page (stringValueEvent)="receiveStringValue($event)"></app-product-child-page>
<h1>{{productName}}<h1>

In the sender component (known as ProductPageChildComponent) TypeScript file for the app-product-child-page selector, define a stringValueEvent variable with the @Output() decorator and assign it a new event emitter.

export class ProductPageChildComponent{

  productName: string;

  @Output() stringValueEvent = new EventEmitter<string>();

  constructor() { }

  ngOnInit(): void {
    this.productName= "Sample Product";
    this.stringValueEvent.emit(this.productName);
  }
}

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

Tips for setting up the configuration of @typescript-eslint guidelines

I am in the process of transitioning to @typescript-eslint but I am finding the documentation to be quite inadequate. One specific issue I am facing is the errors like the following: Line 58: Expected a semicolon @typescript-eslint/member-del ...

mat-sidenav is exempt from the fxFlex rules

Having trouble centering the content within . I've attempted various rules but nothing seems to be working. Interestingly, when I apply fxFlex rules to , everything falls into place perfectly. I've gone through trying to set rules for each elemen ...

Efficiently loading Ionic 3 components within a tab with lazy-loading functionality

Need help with adding a new tab to your project using lazy-loading? You can utilize the @IonicPage decorator for setting up a page as the root of a tab. To implement this, create a new page: // module import { NgModule } from '@angular/core'; ...

Separating HTML content and text from a JSON response for versatile use within various sections of an Angular 2 application using Typescript

Hello there! I am currently utilizing Angular 2 on the frontend with a WordPress REST API backend. I'm receiving a JSON response from the service, however, the WP rest API sends the content with HTML tags and images embedded. I'm having trouble s ...

Proper positioning of try/catch block in scenarios involving delayed async/await operations

For the past six months, I have been utilizing async/await and have truly enjoyed the convenience it provides. Typically, I adhere to the traditional usage like so: try { await doSomethingAsync() } catch (e) {} Lately, I've delved into experimenti ...

Angular - Facing issues with CORS for every request made

Currently, I am developing an angular 12 application for my university with a java back-end. While testing Angular's http client, I encountered an issue where CORS is blocking my requests. const API_URL = 'http://localhost:9080' @Injectable ...

TimeoutException occurs in Browser when using Visual Studio with ASP.NET and Angular

After waiting for 60 seconds, an error message appeared in the browser when trying to debug. However, after refreshing the browser window and waiting for another 15 seconds, everything seemed to be working fine. An unexpected error occurred during the r ...

Creating a custom directive in Angular 2 that restricts input to text only

I have recently created a directive that specifically allows only numbers by using key codes. However, I've noticed that when I try to copy and paste text into the text box, it accepts the input but does not display it. Is there a way to utilize &apo ...

Instructions for a safe upgrade from ngrx version 2.0 to version 4.0

Is there a direct command to upgrade from ngrx v-2 to ngrx v4 similar to when we upgraded from Angular version 2.0 to version 4.0? I have searched extensively for such a command, but all I could find in the git repository and various blogs is this npm ins ...

How to retrieve cookie value from callback response in Angular?

There are two domains: Angular Application: samlapp.domain.com Node Application: samlapi.domain.com When Node calls the callback with the cookie, it redirects to the samlapp application (samlapp.domain.com/landing) Concern: How can I retrieve the cook ...

Troubleshooting problem with ngb carousel timing interval

I am currently developing a web app for selecting maps in Escape from Tarkov. To enhance the visual appeal of the app, I decided to incorporate an ngb-carousel feature for a smooth animation effect. However, I have encountered a problem where the slides ar ...

Issues arising from the implementation of a multi-item carousel using Flickity in Angular

I am currently attempting to implement a multi-item carousel/content slider in Angular, but I am encountering an issue with the Flickity carousel. The items within the carousel are aligning vertically instead of horizontally, which is not the desired behav ...

Running complex operations within a sorting function just once

I am facing the challenge of sorting an array of objects based on multiple date fields, with the added complexity of excluding certain dates depending on the category. In order to optimize performance, I want to minimize the number of times the getUsefulJo ...

Struggling to grasp the syntax of RxJS filter

Trying to wrap my head around a filter expression in an Ionic/Angular project. Here's the code snippet: private userId$ = this.authService.currentUserAuth$.pipe( filter(user => !!user), map((user) => user.uid) ); The authservice is of ...

Adding a new property to the Express request object type: what you need to know

Recently, I developed a custom middleware that executes specific logic tasks. It operates by transforming the keys to values and vice versa within the req.body. Both the keys and values are strings, with built-in validation measures in place for safety. T ...

Defining data types for an array of objects in a useState hook

I'm having trouble understanding the issue with my code. interface dataHistory { data: string, before: string | number, after: string | number, } I have an interface defined outside of the Functional Component and inside I specify its struct ...

Implement conditional props for a React component by linking them to existing props

In my current project, I am working on a component that has a loading state. The component has an isLoading prop which determines whether the component is currently in a loading state or not: interface CustomImageComponentProps { isLoading: boolean ...

Create a unique type in Typescript that represents a file name with its corresponding extension

Is there a way for me to specify the type of a filename field in my object? The file name will consist of a string representing the name of the uploaded file along with its extension. For instance: { icon: "my_icon.svg" } I am looking for a ...

Automatically generate *.story.ts files when using the Angular CLI to create a component

I'm exploring the possibility of implementing Storybook in my Angular project. My aim is to automatically generate a story file for each component, as manually creating them can be tedious. Therefore, I am looking into ways to automate the generation ...

Tips for implementing constraints in Angular 8 route parameters

In my Angular web application, I am in the process of configuring routes with parameters. How can I add constraints to ensure only specific IDs are allowed? Below is the path defined in my 'app-routing.module.ts' file: {path: 'post/:id&apo ...