1

I want to do a paging, but I'm having some problems. When I select the page number in pagination, the "selected" class is applied to the position and not to the number itself.

My HTML:

<template>
<h2>Paginacion</h2>

<span class="slds-p-horizontal_x-small">
    <a onclick={hadleClickPage} name="1">1</a>
</span>

<template for:each={pageList} for:item="item">
    <span key={item.Id} class="slds-p-horizontal_x-small">
        <a name={item} onclick={hadleClickPage}>{item}</a>
    </span>
</template>

<span class="slds-p-horizontal_x-small">
    <a onclick={hadleClickPage} name={totalPages}>{totalPages}</a>
</span>

My JS:

import {
    LightningElement,
    track
} from 'lwc';

export default class lwc_pagination extends LightningElement {

@track pageList;
@track totalPages;
@track currentPageNumber;
@track pageSize;

connectedCallback() {
    this.pageList = [];
    this.totalPages = 12;
    this.currentPageNumber = 1;
    this.pageSize = 5;
    this.generatePageList();
}

generatePageList() {
    this.pageList = [];

    if (this.totalPages > 1) {
        if (this.totalPages <= 10) {
            let counter = 2;
            for (; counter < (this.totalPages); counter++) {
                this.pageList.push(counter);
            }
        } else {
            if (this.currentPageNumber < 5) {
                this.pageList.push(2, 3, 4, 5, 6, '...');
            } else {
                if (this.currentPageNumber > (this.totalPages - 5)) {
                    this.pageList.push('...', (this.totalPages - 5), (this.totalPages - 4), (this.totalPages - 3), (this.totalPages - 2), (this.totalPages - 1));
                } else {
                    this.pageList.push('...', (this.currentPageNumber - 2), (this.currentPageNumber - 1), (this.currentPageNumber), (this.currentPageNumber + 1), (this.currentPageNumber + 2), '...');
                }
            }
        }
    }
}

hadleClickPage(event) {
    event.preventDefault()
    this.currentPageNumber = parseInt(event.target.name, 10);

    this.template.querySelectorAll("a.selected").forEach(element => {
        element.classList.remove("selected");
    });

    this.generatePageList();
    event.target.classList.add("selected");        
}
}

My CSS:

.selected{
color: black;
text-decoration: none;
}
5

1 Answer 1

1

Putting everything into this method fixes the problem I had

    renderedCallback() {
    this.template.querySelectorAll("a.selected").forEach(element => {
        element.classList.remove("selected");
    });
    this.template.querySelectorAll("[name=\"" + this.currentPageNumber + "\"]").forEach(element => {
        element.classList.add("selected");
    });
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .