Sharing information between Angular components

Having recently started using Angular, I'm facing an issue with passing an array to a different component that is not parent or child related. What I aim to achieve is: upon selecting rows from the first component table, a new view should open up displaying the selected rows.

First component:

openExecutionDialog(): void {
    ....
    dialogRef.afterClosed().subscribe((result) => {
      if (result === true) {
        this.dataService.invocationBulk(new HttpParams(), this.checkedIds).subscribe(
          (changed) => {
            var taskids = Array.from(this.checkedIds.values());
            this.taskService.saveData(taskids)
            
},
          (error) => { 
            ..
      }
    });
  }

taskService:


public tasksSubject = new BehaviorSubject<Task[]>([]);
  data$ = this.tasksSubject.asObservable();
 constructor(
    private dataService: DataService)
  {}
public saveData(taskids: number[]){
    this.dataService.getTasks(taskids).subscribe((data) => {
      this.retryTasks = data;
    });
  }

setTasks(tasks: Task[]) {
    this.tasksSubject.next(tasks);
    debugger
  }
}

The definition of method getTasks is:


getTasks(taskId: number[]): Observable<RetryTaskResource[]> {
    return this.apiDataService.getTasksUrl().pipe(
      mergeMap((rootUrl) =>
        this.http.get<Task[]>(`${rootUrl}${taskId}`)
      ),
      map((result: Task[]) => {
        return result;
      })
    );
  }

Second Component


  dataSource = new MatTableDataSource();
 constructor(private taskService: TaskService) {
this.taskService.data$.subscribe(data => {
      this.dataSource = data;})
}

HTML

<div class="table-container">
        <table
          mat-table
          [dataSource]="dataSource"
          matSort
          matSortActive="zeitstempel"
          matSortDisableClear
          matSortDirection="desc"
        >


           <ng-container matColumnDef="modul">
            <th mat-header-cell *matHeaderCellDef mat-sort-header disableClear>
              Module
            </th>
            <td mat-cell *matCellDef="let row">{{ row.module }}</td>
          </ng-container>

...

I've explored various approaches without success. Upon debugging, I can confirm that the tasks[] in the first component are populated.

2nd Approach from Angular pass array to another (NOT child) component

First Component

...
(changed) => {
   var taskids = Array.from(this.checkedIds.values());
   this.dataService.getTasks(taskids).subscribe((data) => {
              this.markAsAccepted(data)
            });
 }

markAsAccepted(items: Task[]) {
    this.taskService.addToAccepted(items);
  }

taskService

 private acceptedArray: RetryTaskResource[] = [];
  public acceptedArraySubject = new BehaviorSubject<RetryTaskResource[]>[];

addToAccepted(items: RetryTaskResource[]) {
    this.acceptedArray = items;
    this.acceptedArraySubject.next(this.acceptedArray);
  }

Second Component

  acceptedArray: Observable<Task[]> | undefined;
  constructor(....) {
    this.dataService.acceptedArraySubject.pipe(share());

}

Answer №1

why not continue utilizing a service

within your initial component:

onClick = () => {

  this.userService.data$.next( myData );

  //navigate to new view using dialog or router

}

then in your new view:

  @for ( let item of userService.data$ | async; track item ) {

    {{ item.property }}

  }

and within your service:

...
  data$ = new BehaviorSubject([]);
...

EDIT:

The alternate approach is as described above but make sure to include a subscribe() method in your code it should look something like:

  displayedData: Observable<Item[]> | undefined;

  constructor(....) {
    
    this.dataService.displayedDataSubject.pipe(
      share(),
      tap( item => {

        this.displayedData = item;

      })).subscribe();

  }

Answer №2

I'm currently working on a project that involves displaying a list and opening a modal with the selected content when an item from the list is clicked.

Here is the HTML code for the main component:

<div class="container-2">
      <div *ngFor="let item of items; let i=index" class="card" style="width: 9rem;">
<img (click)="getInfo(i)" class="card-img-top" [src]="item.img">
        <div class="card-body">
          <h5 class="card-title">{{item.name}}</h5>
          <p class="card-text">{{item.types[0]}} {{item.types[1]}}</p>
        </div>
      </div>
  </div>

And here is the TypeScript code for handling the modal:

import { MatDialog } from '@angular/material/dialog';

..

constructor(public dialog: MatDialog,) { }
getInfo(index : any){

  let dialogRef = this.dialog.open(InfoComponent,{data:index, width: '40%'});
  dialogRef.afterClosed().subscribe(result => {
    console.log(result)
    console.log('The dialog was closed');
  });
}

Lastly, here is the TypeScript code for the modal component:

import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';

...

constructor (@Inject(MAT_DIALOG_DATA) public data: any,
public dialogRef: MatDialogRef<InfoComponent>){

}
...

You can use the data property to configure and send whatever information you need for the modal component.

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

Customizing TinyMCE's font style menu options

Our platform utilizes TinyMCE as in-place editors to allow users to make live edits to content. However, a challenge arises when using a dark background with light text, as TinyMCE defaults to using this text color rather than black. (Please note: the the ...

A technique for deactivating reactive forms control within a nested formArray

Is there a way to selectively disable individual controls within the 'fields' group which is nested under this.form.get('groups').controls? I know how to disable an entire group by using this.form.get('groups').controls.disabl ...

Ways to resolve the angular error "Encountering an unhandled exception: Unable to locate module 'typescript' "?

I'm encountering errors when running ng serve. I've attempted the following code as well, but I'm still facing the same error: npm install -g typescript Error displayed in text format D:\xampp\htdocs\angular\axen>ng ...

Attempting to invoke a TypeScript firebase function

I'm currently working on incorporating Firebase functions in my index.ts file: import * as functions from "firebase-functions"; export const helloWorld = functions.https.onRequest((request, response) => { functions.logger.info(" ...

Best practices for implementing UI logic in an Angular application

Imagine having an Angular application with two distinct views. One view displays a basic preview of an object, let's say a car, while the other view showcases detailed information about that specific car. The structure of the car model might resemble ...

Flattening an array of Map in Typescript involves combining all the

I am working with an array containing entries of type Map<string, number> Is there a way to flatten this array into a single map? Map<string, number>[] converted to Map<string, number> Appreciate any help on this matter. ...

Can you explain the mechanics behind the functionalities of @angular and @type dependencies?

This inquiry may have been raised before, but I couldn't uncover all the solutions. If that's the case, my apologies. I have a good grasp on how package.json and dependencies / dev-dependencies function in Node applications. Currently delving i ...

What steps can be taken to resolve the Angular error stating that the property 'bankCode' is not found on type 'User' while attempting to bind it to ng model?

I'm encountering an issue with my application involving fetching values from MongoDB and displaying them in an Angular table. I've created a user class with properties like name and password, but I keep getting errors saying that the property doe ...

Discovering the data type in Typescript through the use of Generics

In my data structure, I am using generics to build it. However, when I try to populate data, I encounter the need to convert simple formats into the correct types. The issue arises as the class is configured with Generics, making it difficult for me to det ...

Tips for setting up chrome-app typings in Typescript 2

I am looking to eliminate the typings in our Typescript project. After successfully removing most typings dependencies with Typescript 2, I'm left with just one for chrome-app: https://github.com/uProxy/uproxy/compare/master...fortuna:master When usi ...

A helpful guide on troubleshooting the ngx-bootstrap error within Angular-14

While working on my Angular-14 project, I encountered an issue with the package.json file: This is how my package.json looks like: "dependencies": { "@angular/animations": "^14.0.0", "@angular/common": "^14 ...

Angular dependency issue: Expected '{' or ';' for @types/node

I encountered an error while running "ng serve" in my Angular application. Originally built as Angular 2, it was upgraded to Angular 8 (with attempts at versions 6 and 7 along the way). However, after migrating from Angular 5, I started experiencing errors ...

Is there a feature in Angular 2+ (specifically Angular 7) that allows for comparing code differences

Is there a code comparison component or plugin available for Angular 2+ (specifically Angular 7) that can compare two separate text files? In our current AngularJS application that we are upgrading, we currently use Ace-Diff and it works effectively. Howe ...

Within an Angular test scenario, execute a static method from a service that triggers an HTTP get request to fetch stored JSON data. This data is then retrieved and returned back to the service

Currently, I am facing a challenge in my Angular test case where I am trying to load JSON data via an HTTP call. The issue arises when a static method is called from a service spec file named "url-service.spec" to another service named "load-json.service. ...

How to efficiently fetch Redux state through reducers with an action-based approach

Utilizing Redux actions to manage a list of contacts, I am facing an issue where I am unable to retrieve the actual state contact. Despite setting the contact in the action, all I receive is the contact set within the action itself. Can someone guide me on ...

Can you customize the "rem" values for individual Web Components when using Angular 2's ViewEncapsulation.Native feature?

I'm interested in creating a component with ViewEncapsulation.Native that utilizes Bootstrap 4 while others are using Bootstrap 3. Below is the component code with Bootstrap 4: import { Component, ViewEncapsulation } from '@angular/core'; i ...

MUI: Transforming the uncontrolled value state of Select into a controlled one with a new component

I'm attempting to develop an edit form for modifying data fetched from a database based on its ID. Here is what I have tried: import React, {FormEvent, useEffect, useState} from "react"; import TextField from "@material-ui/core/ ...

Why am I encountering numerous errors while attempting to install Juice Shop?

My attempt to install the juice shop app from GitHub resulted in 63 errors showing up after running the command npm install. [riki@anarchy]: ~/juiceShop/juice-shop>$ npm install (Various warnings and engine compatibility issues) Multiple vulnerabilit ...

Adjusting the transparency of TabBadge in Ionic 2

I am currently working on a project that involves tabs, and I'm looking to update the style of the badge when the value is 0. Unfortunately, I am unsure how to dynamically change the style of my tabs or adjust the opacity of the badge in the style. M ...

When a module is generated, it appends an additional slash to the path in the app.module.ts file

I've noticed a strange behavior with the generator in Angular CLI tools that adds an extra slash character for modules. For example, when running ng generate component visual a line like this is added to the app.module.ts file import { VisualCo ...