Maintaining the ngFor value when clicked and passing it to another component

Currently tackling an angular project and seeking assistance with a particular issue...

I have successfully displayed data from an array, but now I am looking to store the value of the element I click on so that I can utilize it in another component along with an API link

Here is the code snippet for the component responsible for displaying the data

<div class="popup-content">
<ul class="list-group">
    <li  mat-dialog-close
        routerLink='/admin'
        *ngFor="let t of data"
        class="list-group-item">
        {{t}}
      
</li>
</ul>
</div>

How can I capture and save the value of 't' upon clicking, so that it can be accessed in another component?

The data array initialization looks like this

this.service.getPosts()
      .subscribe(response => {
        this.posts = response;
        this.num = this.posts.body.paginationinfo.numberofelementsTotal;

        for(this.i=0;this.i<this.num;this.i++)
        {
          this.test.push(this.posts.body.listOfUnapprovedChangeRequests[this.i].requestuuid);
        }
        
      });

      console.log(this.test);
  }

  openDialog(){
    this.dialogRef.open(MenupopupComponent,{data:this.test})
  }

Answer №1

To send information as a query parameter, you can do so by including it in the URL.

<ul class="list-group">
  <li
    mat-dialog-close
    routerLink="/admin"
    [queryParams]="{ requestId: t }"
    *ngFor="let t of data"
    class="list-group-item"
  >
    {{ t }}
  </li>
</ul>

Retrieve the requestId query parameter using the ActivatedRoute:

export class AdminComponent {
  constructor(private route: ActivatedRoute) {}

  ngOnInit(): void {
    const requestId = this.route.snapshot.paramMap.get('requestId');
    console.log('requestId', requestId);
  }
}

Answer №2

There exist numerous approaches for sharing data among components,

  1. Passing Data from Parent to Child Components: using Input bindings
  2. Emitting Events from Child to Parent Components: utilizing Output() and EventEmitter
  3. Accessing Elements in Child Component from Parent Component: through ViewChild decorator
  4. Communicating between Unrelated Components: by employing a Service

In your specific scenario, the most suitable option is the 4th one (utilizing a Service).

To implement this, you can define a variable in the service and set its value when an li element is clicked. Subsequently, you can access this value in another component.

For further information, please visit:

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 jwt tokens transmitted from the frontend to the backend

Having just started learning Django and simplejwt, I'm facing an issue with retrieving tokens sent from our Angular frontend labeled as "app_token" and "access_token". Despite trying variations like "HTTP_APP_TOKEN" and "HTTP_ACCESS_TOKEN", as well as ...

"Troubleshooting issues with data loading using React's useEffect function

While working on my project, I encountered a strange issue where the isLoading state is being set to false before the data fetching process is completed. I am using the useEffect hook to show a loading spinner while fetching data from an API, and then disp ...

Reconnect automatically SignalR client upon server restart

I am currently using ASP.NET Core SignalR within the ASP.NET Boilerplate project, and everything runs smoothly while the server is running. However, whenever I need to restart the server for any reason, I encounter these errors: https://i.sstatic.net/Thr ...

invoking a function in one component from another component within an Angular 4 project using ng-smarttable

Utilizing ng-smarttable to display data in a table and have successfully added a custom button in a separate component. However, I am encountering an issue where the data does not reload when clicking on the button. An error message is appearing: ERROR Ty ...

Find the dominant color within the project's style sheets

Is there a method to extract the main color from an angular material theme and apply it in the css files of an angular project? Within a project, we can specify the primary color in a *.scss document as shown below: @import '~@angular/material/themi ...

Not all Angular Material2 styles are being fully applied

One issue I am encountering is that styles for components such as <mat-chip> or <button mat-raised-button> (the only ones I have found) are not working properly and appear gray by default. However, styles do apply correctly to the <mat-card& ...

Eliminating data type from union in Typescript

I have a specific type that I collect from various other types: type CustomType = { id: string; foo: (string | Type1)[]; bar: (string | Type2)[]; baz: string | Type3 | null; description: string | null; } I am interested in refining thi ...

NestJs encountering issues with reading environment variables

I used the instructions from the Nest documentation to set up the configuration, however, it's not functioning correctly. app.module.ts @Module({ imports: [ ConfigModule.forRoot({ isGlobal: true }), TypeOrmModule.forRoot(config), AuthMo ...

When using TypeScript, my sorting function returns a value of 0 for all time values

I have been trying to sort this JSON data by date using the provided code, but it does not seem to work as expected. Below is a snippet of my JSON: { "StatusCode":0, "StatusMessage":"OK", "StatusDescription":[ { "id":"1", ...

How to pass a String Array to a String literal in JavaScript

I need to pass an array of string values to a string literal in the following way Code : var arr = ['1','2556','3','4','5']; ... ... var output = ` <scr`+`ipt> window.stringArray = [`+ arr +`] & ...

Can you explain the purpose of the argument provided to @Resolver in type-graphql?

I'm genuinely curious about something. I noticed on the type-graphql documentation website that they include an argument in the @Resolver decorator. You can see this in action on their page here: (look under the "Resolvers" section). Here is a snipp ...

What is the proper place for DOM manipulation within Angular 2?

When it comes to Angular 2, the rules around DOM manipulation have evolved from Angular 1. In Angular 1, all DOM manipulation was supposed to be handled in directives for proper testability. However, with Angular 2, there seems to be a lack of clear inform ...

Error encountered while installing Material UI in Next.js with TypeScript and pure JavaScript configurations

I'm brand new to React and Next.js, so please forgive me for asking what may seem like a silly question. I'm attempting to install Material UI in a fresh Next.js application that I created using "npx create-next-app@latest". I've been refere ...

Troubleshooting: Unable to filter reducers in Redux when using the remove

I'm attempting to eliminate an element from an array using the filter method in this manner: removeDisplate: (state, action: PayloadAction<string>) => { console.log(action.payload); state.map((item) => { console.log(item.name); } ...

Jasmine test case for Angular's for loop (Error: Expected the length of $ to be 11, but it should be 3

While creating test cases for a loop in Angular (Jasmine), I encountered an error: Error: Expected $.length = 11 to equal 3.. The loop is supposed to generate an array of arrays similar to const result. Can someone point out what I might have missed here? ...

"Utilizing Angular's RxJS to efficiently filter an observable

I am currently attempting to filter a stream of products using an array of filters, but I am unsure of the best approach. Let me clarify my goal: I want to store the filtered result in the variable filteredProducts. To perform the filtering, I need to ite ...

Issue with refreshing causing Firebase Hosting (utilizing Angular 8 and Service Worker) to not update

I am the owner of quackr.io and I am encountering an issue where users are not seeing the updated version of my code. Quackr is a Progressive Web App (PWA) built with Angular SSR and Service worker, deployed on Firebase hosting. Every time I deploy a new ...

What are the best practices for configuring Angular in a NodeJS Express Server for production deployments?

After spending hours working on deploying my Angular 6 project on a NodeJS Express server, I encountered some challenges. During development, I used ng serve which runs on localhost:4200 by default, and Node Express for API (interacting with the database) ...

Encountering a stumbling block with Jest in Ionic 6 and Angular 14? Learn how to properly configure Jest to avoid unexpected token

I'm encountering an error while setting up Jest for Ionic 6 and Angular 14 with the @awesome-cordova library. Jest.config.js const { pathsToModuleNameMapper } = require('ts-jest'); globalThis.ngJest = { skipNgcc: false, tsconfig: ' ...

Exploring the integration of the mongodb-stitch library within an Angular 4 application

I have been experimenting with the MongoDB Stitch service in Angular, and so far I have successfully implemented the service. However, the only way I have managed to connect to the service is by adding the js library hosted on AWS directly into the html pa ...