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

Determine whether the ng bootstrap modal has already been opened

Is there a way to determine if a modal window is open? In order to accomplish this, I create a variable called modalInstance: NgbModalRef; and initialize the modal by using the code below this.modalInstance = this.modalService.open(UpdateModalConten ...

The fuse-sidebar elements are not being properly highlighted by Introjs

I have recently developed an angular project that utilizes the fuse-sidebar component. Additionally, I am incorporating introjs into the project. While introjs is functioning properly, it does not highlight elements contained within the fuse-sidebar. The ...

Issue with Angular9-MatDatePicker: Unable to establish a connection with 'ngModel' as it is not recognized as a valid attribute of 'input'

Despite my efforts to implement ngmodel binding with matdatepicker, I am still encountering issues, even after reviewing multiple other posts on the topic. Here is a snippet of my HTML: <mat-form-field> <mat-label>Start Date</mat-label ...

JavaScript has a feature called "functions" which allow the declaration of named blocks of

Currently, I am developing an Electron app in typescript. In my main.ts file, I have instantiated a custom CommunicationProvider class object. What I want is for this class to declare multiple methods (specified in an interface that it implements) but have ...

Tips for Decreasing Query Time with MatTable and MatTableDataSource

When working with my firestore database, I am trying to query documents and display them while also calculating the total value of a specific column (promiAmount). I have successfully displayed the values in a mat table, but I'm struggling to calcula ...

React.js: You cannot call this expression. The type 'never' does not have any call signatures

Could someone help me troubleshoot the error I'm encountering with useStyles? It seems to be related to Typescript. Here's the line causing the issue: const classes = useStyles(); import React from "react"; import { makeStyles } from & ...

Setting up grunt-ts to function seamlessly with LiveReload

I am currently experimenting with using TypeScript within a Yeoman and Grunt setup. I've been utilizing a Grunt plugin called grunt-ts to compile my TypeScript files, and while the compilation process is smooth, I'm encountering issues with live ...

Using the moment library in Angular to convert date and time can sometimes lead to errors

Whenever I attempt to convert a Gregorian date to a Persian date, the minute value in the conversion ends up becoming an error. For instance, let's say I want to convert this specific date and time to a Persian date: 2020-09-14T16:51:00+04:30 should ...

What is the best way to pass an array as a parameter in Angular?

I have set up my routing module like this: const routes: Routes = [ { path: "engineering/:branches", component: BranchesTabsComponent }, { path: "humanities/:branches", component: BranchesTabsComponent }, ]; In the main-contin ...

What are the solutions for handling undefined data within the scope of Typescript?

I am encountering an issue with my ngOnInit() method. The method fills a data list at the beginning and contains two different logic branches depending on whether there is a query param present (navigating back to the page) or it's the first opening o ...

Compiling with tsc --build compared to tsc --project

I'm currently working on converting a subproject to TypeScript within my monorepo. Within my npm scripts, I initially had: "build-proj1":"tsc --build ./proj1/tsconfig.json" Although it did work, I noticed that the process was unus ...

Customize the border color of a dynamic textbox with Angular

I'm using Angular to create dynamic textboxes. <span *ngFor="let list of lists[0].question; let i = index"> {{ list }} <input type="text" *ngIf="i != lists[0].question.length-1" [(ngModel)] ...

The array does not yield any values when utilizing Angular CLI

Recently, I created a component that contains an array of strings. Here's the code snippet for reference: import {Component} from '@angular/core'; @Component({ selector: 'app-products-list', templateUrl: './products-list. ...

Distribute your SolidJS Typescript components on npm

Recently, I developed a SolidJS TypeScript UI component and successfully published it to the npm registry. The project structure is organized as follows: |-app |-index.html |-src |-index.tsx |-App.tsx |-utils |- ... |-com ...

React is struggling to locate the specified module

Once I've set up my react project using npx create-react-app called my-app, I proceed to run npm start only to encounter the error shown in the image below. Running node version: 12.16.1 with npm version: 6.13.4 View the error message her ...

Tips for displaying only the components associated with the user's role in Angular

Greetings everyone! I have a dashboard that features a menu showcasing all the components. I am looking to implement a functionality where, if logged in with the admin role, all components should be displayed. On the other hand, if logged in with the respo ...

Impact when returning a React.FC Component

Using React, I have encountered a challenge with my site: I have a function that generates a Card component displaying information about my store's products (#1). To display this on the screen, I map through the array returned by the backend and pass ...

Issue encountered in Loopback 4: Error with @repository dependency injection (TypeError: Undefined property 'findOne')

As I set up Bearer Token authentication for my Loopback 4 application, I referenced this implementation guide: https://github.com/strongloop/loopback-next/tree/master/packages/authentication. Within my src/providers/auth-strategy.provider.ts file, I encou ...

Creating a primary index file as part of the package building process in a node environment

Currently, I have a software package that creates the following directory structure: package_name -- README.md -- package.json ---- /dist ---- /node_modules Unfortunately, this package cannot be used by consumers because it lacks an index.js file in the r ...

What is the best way to extract a nested array of objects and merge them into the main array?

I've been working on a feature that involves grouping and ungrouping items. A few days ago, I posted this question: How can I group specific items within an object in the same array and delete them from the core array? where some helpful individuals ...