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

Unable to retrieve a substring value in Angular using Typescript

html <p> <input type="text" maxlength="40" (input)="recipientReference = deleteSpacing(recipientReference)" [(ngModel)]="recipientReference" style="width: 30vw; padding: 5px;border: 1px solid;border ...

What is the Correct Way to Send Functions to Custom Directives in Angular 2 Using TypeScript?

I am relatively new to Angular 2. I am currently in the process of upgrading my application from AngularJS and focusing on completing the UI/UX development. There is one final issue that I am seeking help with, and I appreciate any assistance provided. Cu ...

Issue updating Bootstrap in ASP.Net Core 2.1 with Angular Template

Every time I start a new ASP.Net Core 2.1 project with the angular template and try to update the bootstrap version from 3 to 4 in package.json, it ends up breaking my application. Despite numerous attempts such as deleting the node_modules folder and rein ...

What is the reason behind the success of 'as' in ngFor compared to '='?

<tr *ngFor = "let item of list; let i = index;"> An issue arises with the code above: The error message reads: Type 'number' is not assignable to type 'string'. td [ngModelGroup]="j" #temp="ngModelGroup ...

TimeStamp Recorder - Typescript

I'm trying to create a timer that counts the time when a button is pressed. Currently, I have managed to display the minutes and seconds on the screen as soon as the button is clicked. For example: 21(min):02(sec) What I am struggling with is updati ...

Connecting Angular Material DataTable to data sources

I am currently utilizing Angular Material and trying to integrate the DataTable with an Http response object. Although I have set up the DataSource and the table rows are being populated, none of the content is displaying in the table. Each object in the c ...

Issue with TailwindCSS @apply not compiling in Angular v12 component styles

I am a computer science student working on a project for my studies. I am currently developing a component library for the Angular framework using Angular V12. To style the components, I have decided to use Tailwindcss as it simplifies some aspects like me ...

Discover the combined type of values from a const enum in Typescript

Within my project, some forms are specified by the backend as a JSON object and then processed in a module of the application. The field type is determined by a specific attribute (fieldType) included for each field; all other options vary based on this ty ...

Managing the behavior of screen readers when interacting with forms

I have a form in my Angular 2 application with input fields. The JAWS 18 screen reader reads the input fields one by one when the page is loaded. I want to customize this behavior so that the screen reader only mentions the form and then stops. I tried u ...

(React Native - Expo) The hook array fails to include the most recently selected object

When I attempt to add objects to a hook within a component, it seems to be functioning correctly. However, there is an issue where the last selected object is consistently missing from the updated hook array. This behavior also occurs when removing an obje ...

Retrieve specific files from a Firestore collection based on a particular field

I am currently working on a web application using Angular 6 and angularfire2. I have successfully retrieved all documents in a collection, but now I need to filter those documents to only get the ones with the field role.moderator == true. private users ...

The functionality of the Ionic 4 app differs from that of an Electron app

I've encountered an issue with my Ionic 4 capacitor app. While it functions properly on Android studio, I'm having trouble getting it to work on Electron. Any ideas on how to resolve this? Here are the steps I took to convert it to Electron: np ...

Submitting Angular data to PHP back-end is a common practice

I am attempting to send data from Angular to PHP. Angular POST Request var body = { "action":"getvouchernumber","vouchertype": vtype, "vmonth": vmonth, "vyear":vyear }; return this.http.post(this.BaseURI+& ...

Ways to obtain the component reference when clicking in Angular 2?

<!--snippet from template file--> <custom-element ... other attributes (click)="handleClick()" </custom-element> @Component({ //selector and templateUrl }) class MainComponent{ handleClick(){ // Obtaining the re ...

Where specifically in the code should I be looking for instances of undefined values?

One method in the codebase product$!: Observable<Product>; getProduct(): void { this.product$ = this.route.params .pipe( switchMap( params => { return this.productServ.getById(params['id']) })) } returns an ...

Ways to dynamically display components in React Native

In my React Native app, I have a custom tab control that is rendered dynamically using the following configuration: const TABS = [ { title: 'Tab 1', component: MyComponentOne }, { title: 'Tab 2', component: MyComponentTwo } ]; T ...

TypeScript Tutorial: How to retrieve the data type of a deeply nested object

I have a question about extracting the type of a nested object with similar structures. The object in question contains multiple sub-objects that all follow the same pattern. const VALUES = { currentStreak: { display: "Current streak", ...

Only the (click) event is functional in Angular, while the (blur), (focus), and (focusout) events are not functioning

I have a unique HTML element as shown below <div (hover)="onHover()" (double-click)="onDoubleClick()" (resize)="resize()" (dragend)="dragEnd()"> These 4 functions are designed to display information onHover ...

Retrieve the overall number of job openings from the Github Job API

I have successfully created an Angular application that mirrors the functionality of However, I encountered a limitation where only 50 positions are available per page, To fetch additional jobs beyond the initial 50, I need to append "?page=X" to another ...

Can the string literal type be implemented in an object interface?

My custom type is called Color, type Color = 'yellow' | 'red' | 'orange' In addition, I created an object with the interface named ColorSetting. interface ColorSetting { id: string yellow?: boolean red?: boolean orang ...