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

Contrasting the double dash without any arguments versus the double dash with a specific argument, such as "no-watch."

For instance, when attempting to run unit tests for an Angular app, the following command is used: npm run test -- --no-watch --browsers=ChromeHeadlessCI I know that two dashes (--) are required to pass arguments into the npm script. However, I'm con ...

Custom styles for PrimeNG data tables

Struggling to style the header of a datatable in my Angular project using PrimeNG components. Despite trying various solutions, I am unable to override the existing styles. Even attempting to implement the solution from this PrimeNG CSS styling question o ...

challenge communicating between Angular and Node using CORS plugin

I've been researching how to enable CORS in node/express and have tried implementing various solutions, but without any success. Here is my angular request: function getPhotos(location) { var url = 'https://api.instagram.com/v1/media/sear ...

What is the Angular alternative to control.disable when working with a QueryList?

I have encountered a challenge in my Angular form where I need to disable certain fields. The issue arises from the fact that many of the HTML tags used are customized, making it difficult to simply use the disabled attribute. To address this, I have opted ...

Assigning a specific data type to an object in TypeScript using a switch case statement

I am currently developing a React Native app using TypeScript. As part of my development, I am creating a handler with a switch case structure like the one below: export const handleMessageData = (dispatch: Dispatch, messageData: FCMMessage): void => ...

Modifying the color of the error icon in Quasar's q-input component: a step-by-step guide

https://i.stack.imgur.com/4MN60.png Is it possible to modify the color of the '!' icon? ...

The 'asObservable' property is not present on the type '() => any'.ts(2339)

Error: Property 'asObservable' does not exist on type '() => any'.ts(2339) Error: Property 'subscribe' does not exist on type 'Subscription'. Did you mean 'unsubscribe'?ts(2551) Error: Property 'sub ...

Having difficulty building a react.js application using Visual Studio 2019

Currently, I am following a helpful tutorial on creating a react.js application using visual studio. At this stage, the tutorial instructs me to open the command prompt and enter the following command: webpack app.tsx --config webpack-config.js (I have ...

Ensuring Function Parameter Usage in Typescript and Angular 5

Currently, I am developing a component using Angular 5 and Ionic 4. My objective is to include a Refresher event to hide the refresh spinner whenever the user triggers the final function to conceal the spinner. Provided below is an excerpt of my code: e ...

Tips for restricting additional input when maximum length is reached in an Angular app

In my Angular 6 application, I am working on implementing a directive that prevents users from typing additional characters in an input field. However, I want to allow certain non-data input keys such as tab, delete, and backspace. Currently, I have an if ...

Managing loading and changing events using Angular, jQuery, and Web API

I am populating a dropdown select using ng-repeat. <select onchange="ChangeMonth()" id="month"> <option ng-repeat="(key,val) in Months" ng-selected="val==ActiveMonth" value="{{key}}"> {{val}} ...

What is the most effective method for integrating Bootstrap CSS into an Angular project?

When incorporating a Bootstrap CSS file into an Angular project that has already been added using yarn add <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f2909d9d868186809382b2c6dcc3dcc3">[email protected]</a>, th ...

The parseFloat function only considers numbers before the decimal point and disregards

I need my function to properly format a number or string into a decimal number with X amount of digits after the decimal point. The issue I'm facing is that when I pass 3.0004 to my function, it returns 3. After reviewing the documentation, I realized ...

Sending data from an Angular 2 application to a Spring MVC Rest API using HTTP POST method

I'm encountering an issue while attempting to perform an angular 2 http post JSON with multiple attributes to Spring MVC using @RequestParam. Despite my efforts of searching for a solution, I have not been successful in binding it to my object. I even ...

angular primeng table has a checkbox to select all checkboxes

Is there a way to check all checkboxes in a table when the checkbox in the table header is clicked? I am currently utilizing angular 12 and primeNG table for this functionality. <p-table styleClass="text-sm" [value]="value" [loading] ...

Struggling to retrieve service information for implementation in the component

I am currently working on a project where: 1. I have created a news.service.ts service file with the following code: 2. Within the service, I have implemented a function named throwData() that returns the service data. Here is the code snippet: im ...

Utilize Typescript compiler to identify mistakes during object property access using square brackets

Is it possible to configure the Typescript compiler to identify errors when accessing object properties using square brackets? I have inherited a codebase where object property access is predominantly done with square brackets (obj['myProp'] ins ...

md-table Using FirebaseListObservable as a DataSource

I am currently working with a FirebaseListObservable and a BehaviorSubject that is listening for an input filter. The goal now is to merge these two entities in order to return an array that has been filtered based on the input value, which will then be us ...

Event that occurs when modifying a user's Firebase Authentication details

Monitoring User Actions with Firebase Authentication Within my application built using Angular, Node.js, and Firebase, I am seeking a method to track user events such as additions, modifications, and deletions. Is there a mechanism to recognize when a us ...

You cannot assign multiple properties with the same name to an object literal

I am facing an issue with two validator functions in my TypeScript file. The first validator checks if a user enters a new password same as the old one, displaying an error if so. The second validator ensures that "new password" and "confirm password" must ...