Retrieving unique information from an angular modal using ngFor loop

I'm a beginner in Angular and I have a question that might seem basic, but I couldn't find the solution anywhere. Here it is:

When retrieving data from an API with multiple projects, I want to display information about each project on a dashboard. Additionally, I need to have a button for each project that, when clicked, will display that project's URLs.

Currently, I am using ngFor in the HTML to loop through and display the project information effectively. However, I'm facing challenges implementing the modal functionality. I want to load custom data (from the ngFor) into the modal.

The problem lies in the fact that the modal template is placed at the bottom of the HTML, causing the original ngFor data to be inaccessible when trying to populate the modal.

So far, the only progress I've made is assigning an ID to the button. But how do I use this ID to fetch data from the API?

HTML:

<div *ngFor="let project of projectData; index as i">
  <button
    type="submit"
    id="myModal"
    style="background-color: #f27704; padding: 0px"
    class="btn btn-sm ModalLaunch"
    data-id="{{ project.id }}"
    (click)="open(content)"
  >
    Launch modal
  </button>

  <!-- some other repeatable HTML here -->
</div>
<ng-template #content let-modal>
  <div class="modal-header">
    <h4 class="modal-title" id="modal-basic-title">URLs</h4>
    <button type="button" class="close" aria-label="Close" (click)="modal.dismiss('Cross click')">
      <span aria-hidden="true"&bt;&times;</span>
    </button>
  </div>
  <div class="modal-body">
    <!--        {{project.urls}}-->
    <div class="modal-footer">
      <button type="button" class="btn btn-outline-dark" (click)="modal.close('Close click')">Close</button>
    </div>
  </div>
</ng-template>

This is the open function in the app.component.ts file

open(content) {
    this.modalService.open(content, { ariaLabelledBy: 'modal-basic-title' }).result.then(
      result => {
        this.closeResult = `Closed with: ${result}`;
      },
      reason => {
        this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
      }
    );
  }

I have not been able to figure out how to include the modal template inside the ngFor loop to make the data accessible. I understand that I need to work with the content variable, but how and where should I define it to pass it to the modal?

Answer №1

To initialize the dialog, remember to assign values to the data attribute.

  /**
   *
   */
  opendialog(): void {
    const dialogRef = this.dialog.open(YourComponent, {
      width: '100%',
      // height: '1800',
      data: datatopass,
    });

Ensure that your component can access this data by including it in the constructor.

 constructor(
    @Optional() public dialogRef: MatDialogRef<TickertagsComponent>,
    @Optional() @Inject(MAT_DIALOG_DATA) public data: typeofdatayoupassed,
    
  ) {}

You can then retrieve and use the passed data from the data property.

Please note that this example is specific to Angular Material library. More information can be found here.

Answer №2

Success! I managed to solve the issue by extracting the element ID from the button using a JavaScript function. This ID was then passed on to another function which searched for it in the API JSON, retrieving the relevant data and displaying it using innerHTML. Big thanks to all those who took the time to read and provide feedback on my post!

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

The React router Link appears to be updating the URL, but is failing to properly redirect the user

While utilizing react-router, everything seems to be functioning properly. However, when I attempt to change the :id in the URL, the page does not redirect as expected. <Route path="/school/:id" component={School}/> For example, if I am currently ...

What is the best way to organize a massive file over 10Gb filled with words?

I've been presented with this interview query: You have an input file containing words (which could be a jumble of letters) separated by commas, and the file size is 10 GB or more. Can you devise an algorithm to sort all these words? Keep in min ...

toggle classes using jQuery when a link is clicked

I'm currently working on a jQuery function that will apply a class to a selected link (which opens a page in an iframe) and then remove that class when another link is chosen. Previously, I received assistance from another member for a similar task in ...

Angular 2: Unable to locate the definition for 'Subscription'

When I attempt to define the type of an attribute, I encounter the error Cannot find name 'Subscription'. Where should I import it from? import { Component, OnDestroy, OnInit } from '@angular/core'; import { ActivatedRoute, Router } fr ...

Trigger the download of the PDF document - Angular version 6 or higher

Is there a way I can download a pdf file from a URL without it opening in a new browser tab? I tried using the window.open() method but it didn't work as expected. downloadPDFFile() { window.open('https://www.w3.org/WAI/ER/tests/xhtml/testfi ...

A guide on obtaining meta tag content values and calculating their average

Currently, I am in the process of developing a website that makes use of Schema.org microdata to provide structured content for product listings. One thing I have come across is that Google requires an aggregate rating based on all the reviews. How can I e ...

Step-by-step guide for properly transferring PHP MySQL data to ChartJs

I am looking to create bar charts and pie charts using ChartJs, with data fetched from php and mysql. Specifically, I want to generate a bar chart that illustrates the statistics of male and female students, along with the total number of students. The des ...

What is the best way to eliminate unwanted or specific files from a file upload using PrimeNG's p-fileUpload component

I am working on implementing file upload functionality where I need to validate the files upon selection and remove them if they are not valid. .html <p-fileUpload #fileUpload name="datafiles" [accept]=FileExtentionValue [url]=" ...

Using Javascript, capture user input to execute a search function without the need for a submit button

I am attempting to retrieve input from a textbox and utilize that value to conduct a search without the need for a submit button. The goal is for the search results to be displayed on the page as soon as the content in the textbox changes. I have been br ...

Internet Explorer 8 is not compatible with jQuery fadeIn and fadeOut functions

Recently, I created a script that allows for fading in and out an error container. Surprisingly, it seems to work perfectly in Firefox and Chrome but unfortunately fails to function altogether in Internet Explorer 8. If you're interested, feel free t ...

"Utilize Angular's $http options for requesting instead of using

When I attempt to send a $http POST request to a server API, the request method unexpectedly changes to OPTIONS. Strangely, this issue only occurs when working with localhost. To troubleshoot, I tried making the same request using Postman and it worked fla ...

Update the array with the new data by setting the state

Is it possible to edit and save data in an array while iterating through it using this.state.data.map()? If so, what is the best approach to achieve this? Check out this live example for reference. Below is a sample code snippet: class App extends React ...

error displays stating that the module '../util/http_util' cannot be located

I'm currently using node and Notepad++ to develop a website that allows users to log in, save their details, and access the site. I've encountered an issue that I can't quite figure out even though everything seems fine in the code. Below yo ...

Having issues with async/await functionality within Vue 3's composable functions

Within my project, I implemented a function that handles file downloads. This function, onDownload, is triggered when the download button is clicked: import {useOnDownload} from "../../use/useOnDownload" setup() { ... const loading = r ...

Ensuring the accuracy of input data in all input fields with the help of dojo

1)In my Dojo widget, I have two additional widgets loaded inside. If I need to clear all text boxes within the widget, I currently use this method: this.myAttachPoint.value="". Is there an alternative code that can achieve the same result without adding ...

propagate the amalgamation of tuples as an argument

I'm working with a function that returns a union type of tuples. I need to pass this return value to another function that can accept all its forms using the spread operator .... type TupleUnion = readonly [number, number] | readonly [number, number, ...

Utilizing the Node.js File System to Store Distinct File Names

I am utilizing the Node File System to save uploaded images. My approach involves using a while loop to check for existing file names and incrementing them until a unique file name is found. However, I have encountered issues with my code. I keep receivin ...

What is the best way to pass `response` data between routes in Express when setting up PayPal subscriptions?

I'm currently in the process of integrating PayPal subscriptions into my Node.js application using Express. I've come across a challenge when trying to pass the subscription ID obtained from PayPal's /create-subscription route to the /execut ...

Employing multiple @input() decorators in Ionic 4

I have developed an ionic 4 application One of the components in the app is a message component that displays an error message based on the input it receives. <control-messages [control]="saveUserForm.get('age')"></control-messages> ...

What is the best way to create Jest unit tests for an Angular Component without using TestBed?

I'm diving into the world of Jest testing and feeling lost as to why my tests keep failing. If you have any recommendations for videos or articles that focus on writing Jest unit tests for Angular components and services without using "TestBed," plea ...