Retrieve user-specific information through a modal when the API is clicked

I am currently facing an issue where I am only able to retrieve the user ID or first name, but not all the details at once in the modal popup. My goal is to display specific user data in the modal.

Here is the HTML code:

<table class="table table-striped ">
      <thead>
        <tr>
          <th scope="col">#ID</th>
          <th scope="col">First</th>
          <th scope="col">Last</th>
          <th scope="col">Gender</th>
          <th scope="col">User Detail</th>
        </tr>
      </thead>
      <tbody>
    
        <tr *ngFor="let user of newdata.users;">
          <td>{{user?.id}}</td>
          <td>{{user?.firstName}}</td>
          <td>{{user?.lastName}}</td>
          <td>{{user?.gender}}</td>
          <td>
            <button type="button" class="btn btn-info btn-lg" (click)="openModal()">See Details</button>
          </td>
        </tr>
      </tbody>
    </table>

Although I am able to fetch all the data from the API in the .ts file, my aim is to retrieve one user's data when the button with (open)="openModal()" is clicked.

Here is the .ts code:

  newdata:any = { users: [] };

  constructor (private userAPIData:StudentDataService){}

  selectedUser:any;

  UserClicked(newdata:any){
    let selectedUser = JSON.stringify(newdata);
    // this.selectedUser=newdata;
    alert(selectedUser);
}

  ngOnInit(): void {
    this.userAPIData.getdata().subscribe(res =>{
      // this.newdata= Object.values(res);
      this.newdata = res;
      console.log(this.newdata.users)
  })
  }

  display = "none";
  openModal() {
      this.display = "block";   
  }
  onCloseHandled() {
    this.display = "none";
  } 

Answer №1

Ensure to pass the user object within the method as shown below:

html

(open)="openModal(user)"

ts

openModal(user: any) {
      let selectedUser = JSON.stringify(user); // store user details in this variable
      this.selectedUser=selectedUser;
      alert(selectedUser);
      this.display = "block";   
}

Updated Code:

Remember, you must pass the user object from html into the method and keep it in an array since the popup displayed contains a table. Refer to the stackblitz link below for more!

ts

import { CommonModule } from '@angular/common';
import { HttpClient, HttpClientModule } from '@angular/common/http';
import { Component } from '@angular/core';

@Component({
  selector: 'app-student-data',
  templateUrl: './student-data.component.html',
  standalone: true,
  imports: [CommonModule, HttpClientModule],
})
export class StudentDataComponent {
  newdata: any = { users: [] };

  constructor(private httpClient: HttpClient) {}

  selectedUser: any;

  UserClicked(user: any) {
    let selectedUser = [{ ...user }];
    this.display = 'block';

    this.selectedUser = selectedUser;
    // alert(selectedUser);
  }

  ngOnInit(): void {
    this.httpClient.get('https://dummyjson.com/users').subscribe((res) => {
      console.log(res);
      this.newdata = res;
      console.log(this.newdata.users);
    });
  }

  display = 'none';

  onCloseHandled() {
    this.display = 'none';
  }
}

html

<table class="table table-striped">
  <thead>
    <tr>
      <th scope="col">#ID</th>
      <th scope="col">First</th>
      <th scope="col">Last</th>
      <th scope="col">Gender</th>
      <th scope="col">User Detail</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let user of newdata.users">
      <td>{{ user?.id }}</td>
      <td>{{ user?.firstName }}</td>
      <td>{{ user?.lastName }}</td>
      <td>{{ user?.gender }}</td>
      <td>
        <button
          type="button"
          class="btn btn-info btn-lg"
          (click)="UserClicked(user)"
        >
          See Details
        </button>
      </td>
    </tr>
  </tbody>
</table>

<div class="modal" tabindex="-1" role="dialog" [ngStyle]="{ display: display }">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h4 class="modal-title">User Details</h4>
        <button
          type="button"
          class="close"
          aria-label="Close"
          (click)="onCloseHandled()"
        >
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <p>Model body text</p>

        <table class="table table-striped">
          <thead>
            <tr>
              <th scope="col">#ID</th>
              <th scope="col">First Name</th>
              <th scope="col">Last Name</th>
              <th scope="col">Gender</th>
              <th scope="col">Email</th>
            </tr>
          </thead>
          <tbody>
            <tr *ngFor="let user of selectedUser">
              <td>{{ user?.id }}</td>
              <td>{{ user?.firstName }}</td>
              <td>{{ user?.lastName }}</td>
              <td>{{ user?.gender }}</td>
              <td>{{ user?.email }}</td>
            </tr>
          </tbody>
        </table>
      </div>
      <div class="modal-footer">
        <button
          type="button"
          class="btn btn-default"
          (click)="onCloseHandled()"
        >
          Close
        </button>
      </div>
    </div>
  </div>
</div>

Visit the stackblitz page here

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

Differences in HTML animations can be seen when comparing Google Chrome to Microsoft Edge. Looking for a workaround for autoplay to ensure

My intro video animation is facing recording difficulties due to the autoplay policy in Google Chrome. It seems nearly impossible to capture it accurately. If only autoplay could function for an offline HTML file, my issue would be resolved. Unfortunately ...

What causes TypeScript to overlook the generic constraint within a function?

Here is a simple illustration of what I am trying to convey: type Shape = 'square' | 'circle'; type Params<S extends Shape> = S extends 'square' ? { side: number } : { radius: number }; function getArea<S ...

Automatically fill in form fields with data from a JSON file as soon as the user enters a value

How can I retrieve the bank name, branch, city, and district from a JSON array? Below is the contents of my results.json file: { "ifsc": [{ "ifsc": "PUNB0000100", "bank": "PUNJAB NATIONAL BANK", "city": "ABOHAR ...

Basic jQuery Element Selection

1) Is there a way to trigger an alert only when images like 1_1.jpg, 1_2.jpg, 1_3.jpg or 2_1.jpg, 2_2.jpg, 2_3.jpg are selected and none of the others? (similar to *_1.jpg, *_2.jpg, *_3.jpg) 2) How can I shuffle the order of the image positions randomly ( ...

Loop through the dataset once all the data has been retrieved

My webpage includes a method that utilizes an rxjs service to retrieve data from a server and store it in a Set. Upon attempting to loop through the data in the view and implement a Pipe, I discovered that the Pipe code executes before the entire dataset ...

The ion-slide-box does not update after the active-slide has been changed using $index

I'm currently facing an issue with the controller that corresponds to this specific view. .controller('MenuCtrl', ['$rootScope','$scope','$state','$timeout','$ionicSlideBoxDelegate', functio ...

What are the best practices for managing security on your AWS Amplify web application?

When working with AWS Amplify & DynamoDB in an Angular web app, how can I secure my Amplify resources to prevent unauthorized access from external sources? An important concern lies in exposing the Amplify configuration within the Angular code, making it ...

PHP-based LESS compiler

Is there a way to compile LESS from PHP without using node.js or ruby? I came across a PHP implementation called LESSPHP on Google, but it seems outdated and doesn't support newer features. Would using the V8js API to run less.js work, even though i ...

The function SVGGeometryElement.isPointInFill() may not function correctly in Chromium, but it does work properly in Firefox

I'm currently working on a solution to detect when a path within an SVG file on a canvas has been clicked. The code I've written functions correctly in Firefox, but I'm encountering issues with Chromium browsers. When I surround the code wit ...

The switch statement is not yielding any results

I am currently working on a test that involves processing a string through a switch statement. However, I am facing an issue where the integer value set in the case of the switch statement is not being passed correctly. As a result, the subsequent if state ...

jQuery - Reveal one div while concealing another

I've been working on a script to toggle between two divs onClick - opening one while closing the other if it's already open. I'm fairly new to jQuery and Javascript, having mainly worked with HTML/CSS. Script I found: http://jsfiddle.net/J ...

Leveraging the power of the map function to manipulate data retrieved

I am working on a nextjs app that uses typescript and a Strapi backend with graphql. My goal is to fetch the graphql data from strapi and display it in the react app, specifically a list of font names. In my react code, I have a query that works in the p ...

Retrieve childNodes of the Select All input using jQuery from the container node with the class name "container"

I am trying to retrieve the text value of all the childNodes within the container of the corresponding input when the Select All checkbox is checked. Currently, my code captures the text inside each input label. However, it only logs the label (e.g. &apos ...

Tips for retrieving and storing an HTTP Post response in Angular 4 using HTML formatting

I am currently facing a challenge in Angular 4 where I am trying to retrieve and read the HTTP Post response. However, I am unable to do so because the response is in HTML format. Despite my efforts of researching various sources, I have not been able to f ...

Utilizing Vue.js components and properties to invoke a function

Trying to create a shopping cart button that keeps track of how many times it's clicked, but encountering an issue where the function called by the button doesn't receive the correct parameter. I attempted using {{id}} and :onClick="addThisToCar ...

Using Three.js and EffectComposer to create interactive masking with an UnrealBloomPass

Struggling with dynamically masking an UnrealBloomPass using the EffectComposer and encountering unexpected outcomes. Uncertain if missing a crucial concept or exploring the wrong approach. Any insights would be greatly valued. The composer consists of th ...

Tips for managing child records while the parent record is still being created

When dealing with creating or editing an Excursion record, there is a form that includes nested excursion_images, which are created through a remote call using JavaScript (Fine Uploader). While this solution works perfectly for editing an Excursion, it en ...

Refreshing form fields with sweet alert in Angular 6

Upon selecting the reset option, a confirmation popup will appear to inquire about resetting the high number of fields. Code In .html <button type="button" class="btn btn-danger" (click)="showAlert()">Reset</button> In .ts declare ...

Dealing with Errors - Utilizing Observable.forkJoin with multiple Observable instances in an Angular2 application

One of my Angular applications has two objects, Observable<Object1[]> and Observable<Object2[]>, that call different APIs in the resolver: resolve(): Observable<[Array<Object1>, Array<Object2>]> { const object1 = this.boo ...

The Material UI Menu does not close completely when subitems are selected

I am working on implementing a Material UI menu component with custom MenuItems. My goal is to enable the closure of the entire menu when clicking outside of it, even if a submenu is open. Currently, I find that I need to click twice – once to close the ...