Updating Previous and Next links in an Angular Table following row deletions: A step-by-step guide

I need to implement a feature where row elements can be deleted by enabling checkboxes on the rows and clicking the Delete button. Although I am able to successfully delete items from the table upon clicking the Delete button, I am facing challenges in updating the Prev and Next links according to the page numbers.

Scenario:
Row Id    Row Value

1           Row1
2           Row2
3           Row3

Showing 1-3 of 9 Next //Since it is Page Number 1

Row Id    Row Value

4           Row4
5           Row5
6           Row6

Showing 4-6 of 9 Prev Next // Since it is Page Number 2

Row Id    Row Value

7          Row7
8          Row8
9          Row9

Showing 7-9 of 9 Prev  // Since it is the last page, Next link is disabled.

I'm aiming for a scenario where if the user selects and deletes 7, 8, 9, then 
It should display

Row Id    Row Value

4           Row4
5           Row5
6           Row6

Showing 4-6 of 6 Prev

Html

<button type = "button" (click)="deleteSelectedItems()">Delete Items</button>
<table>
    <thead>
        <th>Row Id</th>
        <th>Row Value</th>
    </thead>
    <tbody>
        <tr *ngFor = "let row of paginatedMessages; let i = index;">
            <td><input type="checkbox" [(ngModel)] = "row.isSelected" (change) = "onCheck($event, row.id, i)" /></td>
            <td>{{row?.id}}</td>
            <td>{{row?.rowValue}}</td>
        </tr>
    </tbody>
</table>
<span> 
    {{paginatedString}}
    <a class = "link" (click) = "showPrevItems()" *ngIf = "showPreviousBtn">Prev</a>
    <a class = "link" (click) = "showNextItems()" *ngIf = "showNextBtn">Next</a>
</span>

ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-pagination-example',
  templateUrl: './pagination-example.component.html',
  styleUrls: ['./pagination-example.component.scss']
})
export class PaginationExampleComponent implements OnInit {

...Remaining TypeScript code...

This issue arises when deleting elements on the last page, causing incorrect updates to the start and end values.

Result:

Row Id  Row Value


Showing 16 - 15 of 15 Prev

If anyone could assist in resolving the problem with updating the Prev and Next links after deleting items, it would be greatly appreciated.

Demo available at StackBlitz

Thank you in advance!

Answer №1

Eliminate the use of boolean values for the buttons.

Instead, consider:

<a class="link" (click)="showPrevItems()" *ngIf="paginatedMessages[0] !== allMessages[0]">Previous</a>
<a class="link" (click)="showNextItems()" *ngIf="paginatedMessages[paginatedMessages.length - 1] !== allMessages[allMessages.length - 1]">Next</a>

Additionally, include logic for handling the last page scenario:

if (
      this.pageNumber >
      Math.ceil(this.allMessages.length / this.noOfMsgsPerPage)
    ) {
      this.pageNumber--;
    }

Updated stackblitz available here:

https://stackblitz.com/edit/angular-ivy-hervkv?file=src/app/app.component.ts

Note: The stackblitz has also fixed the bug related to checkbox array handling. It now filters the array based on the isSelected property.

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

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 ...

Is it necessary to verify the apiKey or does the authentication of the user suffice for an HTTPS callable function?

I'm interested in creating a cloud function that can be executed from both the client and the backend. After exploring the documentation, I learned that an HTTPS callable function will automatically include user authentication data, accessible through ...

Retrieve an instance of the property class within a property decorator

I'm attempting to create a decorator called @Prop that will assist me in adjusting attributes for custom elements. This is the desired code: class MyCustomClass extends HtmlElement { get content() { return this.getAttribute('content&apo ...

What strategies can be used to manage Error return types in Typescript?

I have a situation where I need to handle either an object of type Person or an Error being returned by a function. My goal is to read the values of keys in the returned object only if it's not an Error. The code snippet below throws an error on the ...

The VSCode's intellisense for Angular Material fails to function effectively

In the midst of my project on Angular version 13, I have successfully installed Angular Material using the command below: ng add @angular/material The package has been properly included in the node_modules folder. However, when working with TypeScript ...

various issues with fonts and Uncaught Eval error

I've been encountering multiple font/style errors and an uncaught eval. I have attached a picture for reference. My Angular application is not functioning properly, and I suspect these errors may be the reason. However, I am unsure of their significan ...

Angular 2 offers a powerful feature called ngFor that allows developers to

Is there a way to allow users to enter keywords in an input field to filter items within a list of menu items dynamically without using ngModel? I need this to be done without the use of buttons as well. Any suggestions for a workaround? <div class=" ...

Ensure that the text is wrapped properly when implementing innerHTML functionality

Within my Angular 5 application, I am faced with a requirement to display HTML content retrieved from a database. An example of the text stored in the database is: <div><u>Documents and Files</u></div><ul><li>These docu ...

Whenever I attempt to make changes to the React state, it always ends up getting reset

Currently, I am attempting to utilize Listbox provided by Headless UI in order to create a select dropdown menu for filtering purposes within my application. However, the issue I have encountered is that whenever I update my "selectedMake" state, it revert ...

Is there a way to identify legitimate contacts and phone numbers within an Android application using Javascript or Typescript?

I am developing an Android app where I need to show a list of contacts and specify if they are part of the app's network. However, my goal is to only display valid contacts while excluding unwanted ones such as toll-free numbers or data balance check ...

What is the process for having "export default" convert to "module.exports" during compilation?

In my TypeScript project set to compile to CommonJS, using export default results in it compiling into exports.default instead of module.exports. I am creating an NPM package and need this issue resolved. How can I fix this? I have the tsconfig.json file ...

Using TypeScript to structure and organize data in order to reduce the amount of overly complex code blocks

Within my TypeScript module, I have multiple array structures each intended to store distinct data sets. var monthlySheetP = [ ['Year', 'Month', 'Program', 'Region', 'Market', 'Country', &apo ...

Is it possible to navigate to a particular step during an Angular IntroJS event?

Whenever I attempt to navigate to a specific step from within the IntroJS onexit event, it seems to cause confusion and display the incorrect step along with the highlighted element. I have defined my steps using JSON, with a total of 8 steps: [{ elem ...

Confirming that the NGRX Dictionary value is set

After upgrading from Angular 7.1.4 to 8.2.0 and Typescript from 3.1.6 to 3.5.3, I encountered an issue with identification of array items. Prior to the upgrade, TypeScript correctly recognized that the array item was not undefined. However, post-upgrade, ...

What methods can I use to integrate a Google HeatMap into the GoogleMap object in the Angular AGM library?

I am trying to fetch the googleMap object in agm and utilize it to create a HeatMapLayer in my project. However, the following code is not functioning as expected: declare var google: any; @Directive({ selector: 'my-comp', }) export class MyC ...

How can we direct the user to another tab in Angular Mat Tab using a child component?

Within my Angular page, I have implemented 4 tabs using mat-tab. Each tab contains a child component that encapsulates smaller components to cater to the specific functionality of that tab. Now, I am faced with the challenge of navigating the user from a ...

Enhancing the visual aesthetics of KendoUI Charts through custom formatting

I've been working on a custom visual to showcase some formatted values. After formatting the text and creating a visual, I expected to see the new values displayed. However, the values remain unchanged. Below is my code snippet: valueAxis: { labels ...

What made the "in" operator not the best choice in this situation?

When I set out to create a type that represents the values of a given object type, I initially came up with this: type Book = { name:string, year:number, author:string } // expected result "string" | "number" type ValueOf<T ex ...

Tips for arranging Angular Material cards in columns instead of rows

I am currently developing a web application using Angular, and I've encountered an issue while trying to display cards in a vertical layout rather than horizontally. My goal is to have the cards fill up the first column (5-6 cards) before moving on to ...

Angular directive for converting fields to title case

I have created a custom directive to transform all table column data into titlecase. The directive I implemented is designed to achieve this transformation, keeping in mind that pipes are not being counted: @Directive({ selector: '[appTitleCase]' ...