Acknowledgment Pop-up

When using the PrimeNG table with a custom modal component that I created, I encountered an issue. The edit functionality works correctly and retrieves the correct row id, however, the delete function always returns the id of the first row.

dashboard.html

 <p-table #dt  [value]="iToDoList" dataKey="id"  [paginator]="true" [rowsPerPageOptions]="[10,50,100]"
                             [rows]="10">

                        <ng-template pTemplate="header">
                            <tr>
                                <th>ID</th>
                                <th>Comment</th>
                                <th>Action</th>

                            </tr>
                            </ng-template>
                            <ng-template pTemplate="body" let-row>  
                                <tr>
                                    <td>{{row.id}}</td>
                                    <td>
                                        <div  *ngIf="!row.isEditable">{{row.comment}}</div>
                                        <div *ngIf="row.isEditable">
                                            <input type="text" [(ngModel)]="row.comment">
                                            <span *ngIf="isEmpty(row.comment)" style="color:crimson">Required</span>
                                        </div>
                                    </td>
                                    <td>
                                        <div>
                                            <modal [row]="row"   [disableEditSaveButton]='disableSaveButton'   (deleteRow)="onDeleteToDoList(row)" [showModal]="!row.isEditable"  (selectedRow)="onSelectedRow(row)" (cancelEdit)="onCancelEdit(row)" (save)="onSave(row)"></modal>
                                        </div>
                                        <!--<button (click)="editRow(row)">Edit</button>-->
                                    </td>
                                    <td>                                <button (click)="save(row)">Save</button></td>
                                </tr>
                            </ng-template>

                    </p-table>

dashboard.component

//The issue manifests itself in how the delete method always returns the same id

     onDeleteToDoList(row) {

            console.log('ON DELETe '+ row.id); 

        }

    //The onSave method successfully returns the id of the current selected row
     onSave(row)
         {
            console.log('ON save '+ row.id); 

      }

modal.html

The problem lies within the confirm method which initially returns the correct row id, but when the user clicks "OK", it always shows the id of the first row in the table

    <div>

        <div *ngIf='showModal'>
            <span class="fa fa-edit" (click)="onEdit()">

            </span>&nbsp;&nbsp;
//The confirm method retrieves the right id initially           
<span class="fa fa-trash-o" (click)="confirm()" data-toggle="modal" data-target="#myModal">

            </span>
            <div class="modal fade" id="myModal" role="dialog">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">

                            <button type="button" class="close" data-dismiss="modal">&times;</button>
                            <h4 class="modal-title">Confirm</h4>
                        </div>
                        <div class="modal-body">
                            <p>Delete this record?</p>
                        </div>
                        <div class="modal-footer">
//The onOk method consistently shows the id of the first row
                            <button type="button" class="btn btn-primary" data-dismiss="modal" (click)="onOk()">Yes</button>
                            <button type="button" class="btn btn-default" data-dismiss="modal">No</button>

                        </div>
                    </div>
                    <div>

                    </div>
                </div>
            </div>
        </div>
    </div>

modal.component

    @Output() deleteRow: EventEmitter<any> = new EventEmitter();
        @Output() save: EventEmitter<any> = new EventEmitter();
        @Output() edit: EventEmitter<any> = new EventEmitter();
        @Input() row: any;

    //The onSave method is functioning as expected 
  onSave() {


        this.save.emit(this.row);
    }      
        //This portion is causing the incorrect id to be displayed
        onOk() {

            this.showModal = true;
            console.log("inside " + this.row.id);
            this.deletedRow.emit(this.row);

        }

        //Correctly displays the id
        confirm()
        {
            console.log("confirm " + this.row.id);      
        }

***********************************************UPDATE****************************************** Modal.html

This update has resolved the issue

   <div *ngIf='showModal'>
    <span class="fa fa-edit" (click)="onEdit()">

    </span>&nbsp;&nbsp;
    <span class="fa fa-trash-o" (click)="BeforeModalOpen()"  data-toggle="modal" data-target="#myModal">

    </span>
    <div class="modal fade" id="myModal" role="dialog" >
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">

                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                    <h4 class="modal-title">Confirm</h4>
                </div>
                <div class="modal-body">
                    <p>Delete this record {{row.id}}?</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-primary"  (click)="onOk()">Yes</button>
                    <button type="button" class="btn btn-default" data-dismiss="modal">No</button>

                </div>
            </div>
            <div>

            </div>
        </div>
    </div>
</div>

modal.component

 BeforeModalOpen properly displays the correct ID while onOK continues to show the wrong one.

   BeforeModalOpen() {
    // Reset the sessionStorage if needed
    if(sessionStorage.getItem('tempRow')){
       sessionStorage.removeItem('tempRow');
    }
    console.log("inside BeforeModalOpen " + this.row.id);

    // Convert object to JSON string and store it
    sessionStorage.setItem('tempRow', JSON.stringify(this.row));
}

onOk() {
    // Parse the stored JSON back into an object
    const tempRow = JSON.parse(sessionStorage.getItem('tempRow'));

    // Check for correctness
    console.log("inside " + this.tempRow.id);

    // Emit the event
    this.deletedRow.emit();

    // Close the modal
    $('#myModal').modal('hide');
}

dashboard.component

onDeleteToDoList() {
        const tempRow = JSON.parse(sessionStorage.getItem('tempRow'));

        tempRow.isEditable = false;
        this.showEditOption = false;
        //this.iToDoList.filter(row => row.isEditable).map(r => { r.isEditable = false; return r })
        console.log('ON DELETe '+ tempRow.id);


    }

Answer №1

It's still unclear to me why the value is being lost, but I may have a solution for you.

According to your statement, the value remains intact when the BeforeModalOpen() method is invoked.

Therefore, my suggestion is to create a clone of row and store it in the browser's session storage:

BeforeModalOpen() {
    // Clear sessionStorage before using
    if(sessionStorage.getItem('tempRow')){
       sessionStorage.removeItem('tempRow');
    }
    console.log("inside BeforeModalOpen " + this.row.id);

    // Convert object to JSON string and save
    sessionStorage.setItem('tempRow', JSON.stringify(this.row));
}

Subsequently, when you click Yes and trigger the onOk() function, retrieve the object from session storage and emit it.

onOk() {
    // Retrieve and parse back to object
    const tempRow = JSON.parse(sessionStorage.getItem('tempRow'));

    // Validate
    console.log("inside " + this.tempRow.id);

    // Emit
    this.deletedRow.emit(this.row);

    // Close modal
    $('#myModal').modal('hide');
}

This approach should resolve the issue!

Answer №2

Hello there, it appears that I have identified the issue.

The problematic line of code is right here.

    <button type="button" 
        class="btn btn-primary" 
        data-dismiss="modal" 
        (click)="onOk()">Yes</button>

To be more specific, the culprit seems to be this directive.

data-dismiss="modal"

This particular directive is responsible for closing the modal and clearing its content, inadvertently affecting the processing of 'row' in your onOk() function.

To address this issue, try the following steps.

Firstly: eliminate the directive

    <button type="button" 
        class="btn btn-primary" 
        (click)="onOk()">Yes</button>

Next: handle modal closure within the onOk() function

    onOk() {
        console.log("inside " + this.row.id);
        this.deletedRow.emit(this.row);

        // close the modal after completing operations
        $('#myModal').modal('hide');
    }

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

Showing information from a JSON dataset of users once a specific User ID has been chosen

My task involves displaying user data from an array and then showing the details of the selected user. I attempted to achieve this with the following code: users = USERS; // contains data selectedUser: User; constructor() { } ngOnInit() { } onSelect(i ...

Using Angular 2 to access information from the OpenWeather API

Trying to integrate weather data from an openweather API has presented a challenge. The object received contains an array of 40 objects representing the weather forecast for the next 5 days with a 3-hour interval. The issue lies in displaying this 5-day fo ...

Retrieve an established SQS eventSource in AWS CDK

When working with AWS CDK, there is a built-in function called addEventSource that allows you to easily add new SQS triggers (eventSources) to a lambda function. However, I'm curious if there is a way to access and modify the existing eventSources ass ...

Creating Instances of Variables Within a Class

Currently, I am working on a project using Ionic and Angular. I have come across various ways of instantiating variables and I'm unsure about the implications of each method. Here are three scenarios that confuse me: export class someClass { myVaria ...

Is it possible to apply a formatting filter or pipe dynamically within an *ngFor loop in Angular (versions 2 and 4

Here is the data Object within my component sampleData=[ { "value": "sample value with no formatter", "formatter": null, }, { "value": "1234.5678", "formatter": "number:'3.5-5'", }, { "value": "1.3495", "formatt ...

What is the Angular2 equivalent of the AngularJS $routeChangeStart event?

During our time working with AngularJS, we utilized the $routeChangeStart/End event in the $rootScope to monitor changes in the route object. What is the equivalent method for monitoring route changes in Angular2? How can we achieve the same functionality ...

The collapsible tree nodes overlap one another in the D3.js visualization

I'm currently working on integrating a d3 code into Power BI for creating a collapsible tree structure. Each node in the tree is represented by a rectangular box, but I've run into an issue where nodes overlap when their size is large. Below is t ...

Show real-time validation messages as the form control values are updated

Instructions: Visit Plunker Locate the input box labeled 'Name' Do not enter anything in the 'Name' field Move to the 'Email' field and start typing An error message will appear for the 'Name' field as you type in ...

Initiate a function once the innerHTML content in Angular has been completely loaded

I'm curious to know if it's possible in Angular to receive a notification when the Inner HTML has finished loading. I have a web application that retrieves an SVG image from a server and I need to display it as innerHTML in order to interact with ...

Block users from printing in text input with Angular

I need to restrict users from entering text into a specific input field, even though they can click on it and select the value. Using the disabled attribute is not an option because it triggers another event when clicked. I also want users to have the ab ...

Angular dynamic data internationalization

Incorporating internationalization [i18n] into my angular project has been successful for static content, but I am encountering challenges with dynamic content. Below is a snippet of my code: Static: <div>{{ 'ADD ENTRY' | translate }} &l ...

Integrate a service component into another service component by utilizing module exports

After diving into the nestjs docs and exploring hierarchical injection, I found myself struggling to properly implement it within my project. Currently, I have two crucial modules at play. AuthModule is responsible for importing the UserModule, which conta ...

Angular: Issue with FormArrays not iterating properly

Apologies for the lengthy post, but I needed to provide a detailed explanation of the issue I am facing. In my form, there is a control that contains an array of JSON data. I have created a reactive form based on this structure. Below are the JSON data an ...

What is the best way to insert information into my SQLite database?

Hey there! I'm new to programming and recently started working on an IONIC App. However, I've hit a roadblock. My goal is to create a phone book feature where users can get random JSON contacts and save them to their sqlite database. Here's ...

Utilize dynamic components to load varying data sets multiple times

Is there a way to dynamically load a component multiple times and pass data based on certain values so that it will display with real-time information? I came across an example at the following link: In this example, there is a messageComponent with a "m ...

Ensure your TypeScript class includes functionality to throw an error if the constructor parameter is passed as undefined

My class has multiple parameters, and a simplified version is displayed below: class data { ID: string; desp: string; constructor(con_ID:string,con_desp:string){ this.ID = con_ID; this.desp = con_desp; } } When I retrieve ...

One efficient way to iterate through an object and modify its values in a single line of code

_shop: { [key: string]: string[] } = { fruits: ['Apple', 'Orange'], vegetables: ['Tomato', 'Onions'] } Can a one-liner code be used to modify the values of _shop and return it in a specific format? The desired outp ...

What is the best way to send multiple values from node.js to typescript?

My Node.js post API currently returns a token, but I want it to include the user's email, id, etc: app.post('/auth', function (req, response) { const body = req.body; console.log(req.body); let query = `select * from users wher ...

Angular Universal: Troubleshooting an Unrendered Route

Struggling for hours to make my site Universal and support Server Side Rendering, I came across the issue where the base route '' is not being rendered by the server. Surprisingly, all other routes are functioning properly when directly called fr ...

Issue with angular 8 radio button not being selected

Here is the HTML code I am working with: <div *ngFor="let option of systemEquipmentGroup"> <h5>{{option.optionGroupName}}</h5> <div> <label style="display: block;" * ...