1

Index Number is Starting From Beginning in Second Page When I Use Material (Mat) Paginator I am Storing My Data in Local Storage

My Invite Page (Table)

<table
                            mat-table
                            [dataSource]="dataSource"
                            class="mat-elevation-z8"
                            matSort
                            (matSortChange)="announceSortChange($event)"
                            matSortDirection="desc"
                        >
                            
                            <ng-container matColumnDef="position">
                                <th
                                    mat-header-cell
                                    *matHeaderCellDef
                                    class="head"
                                >
                                    No.
                                </th>
                                <td
                                    mat-cell
                                    *matCellDef="let element; index as i"
                                >
                                    {{ i + 1 }}
                                   
                                </td>
                            </ng-container>

                            <ng-container matColumnDef="name">
                                <th
                                    mat-header-cell
                                    *matHeaderCellDef
                                    class="head"
                                    mat-sort-header="name"
                                    sortActionDescription="Sort by name"
                                >
                                    Name
                                </th>
                                <td mat-cell *matCellDef="let element">
                                    {{ element.name }}
                                </td>
                            </ng-container>

                            
                            <ng-container matColumnDef="email">
                                <th
                                    mat-header-cell
                                    *matHeaderCellDef
                                    class="head"
                                >
                                    Email
                                </th>
                                <td mat-cell *matCellDef="let element">
                                    {{ element.email }}
                                </td>
                            </ng-container>

                          
                            <ng-container matColumnDef="status">
                                <th
                                    mat-header-cell
                                    *matHeaderCellDef
                                    class="head"
                                    mat-sort-header="status"
                                    sortActionDescription="Sort by status"
                                >
                                    Status
                                </th>
                                <td mat-cell *matCellDef="let element">
                                    {{ element.status }}
                                </td>
                            </ng-container>

                            <ng-container matColumnDef="cancel">
                                <th
                                    mat-header-cell
                                    *matHeaderCellDef
                                    class="head"
                                >
                                    Cancel
                                </th>
                                <td
                                    mat-cell
                                    *matCellDef="let element; index as i"
                                >
                                    <!-- {{ element.status }} -->
                                    <button
                                        class="mx-4"
                                        (click)="cancelInvite(i)"
                                    >
                                        <span class="material-symbols-outlined">
                                            cancel
                                        </span>
                                    </button>
                                </td>
                            </ng-container>

                            <tr
                                mat-header-row
                                *matHeaderRowDef="displayedColumns"
                            ></tr>
                            <tr
                                mat-row
                                *matRowDef="let row; columns: displayedColumns"
                            ></tr>
                        </table>
                        <mat-paginator
                            [pageSizeOptions]="[10, 20]"
                            showFirstLastButtons
                            aria-label="Select page of periodic elements"
                        >
                        </mat-paginator>

My Invite Component

import { AfterViewInit, Component, OnInit, ViewChild } from '@angular/core';
import {
    AbstractControl,
    FormBuilder,
    FormGroup,
    Validators,
} from '@angular/forms';
import { UserService } from 'app/services/user/user.service';
import { MatPaginator } from '@angular/material/paginator';
import { MatTableDataSource } from '@angular/material/table';
import { Router } from '@angular/router';
import { FuseConfirmationService } from '@fuse/services/confirmation';
import { ToastrService } from 'ngx-toastr';
import { MatSort, Sort } from '@angular/material/sort';
import { LiveAnnouncer } from '@angular/cdk/a11y';

export function validateName(control: AbstractControl) {
    if (control.value.length < 3 && control.value.length != 0) {
        return { minLength: true };
    } else if (control.value.length > 30) {
        return { maxLength: true };
    }
    return null;
}

export function validateEmailLength(control: AbstractControl) {
    if (control.value.length < 5 && control.value.length != 0) {
        return { minEmailLength: true };
    } else if (control.value.length > 50) {
        return { maxEmailLength: true };
    }
    return null;
}
@Component({
    selector: 'app-invite-user',
    templateUrl: './invite-user.component.html',
    styleUrls: ['./invite-user.component.scss'],
})
export class InviteUserComponent implements OnInit, AfterViewInit {
    public invitedUsers: any = [];
    public users: any = [];
    public filteredUser: any;
    public inviteUserForm: FormGroup;
    public filterStatus: any;
    public updatedStatus: any;

    // showAlert: boolean = false;
    // alert: { type: FuseAlertType; message: string } = {
    //     type: 'success',
    //     message: '',
    // };

    displayedColumns: string[] = [
        'position',
        'name',
        'email',
        'status',
        'cancel',
    ];

    dataSource = new MatTableDataSource<any>([]);

    @ViewChild(MatPaginator) paginator: MatPaginator;
    @ViewChild(MatSort) sort: MatSort;

    constructor(
        private fb: FormBuilder,
        private _userServices: UserService,
        private router: Router,
        private _fuseConfirmationService: FuseConfirmationService,
        private _toastr: ToastrService,
        private _liveAnnouncer: LiveAnnouncer
    ) {}

    ngOnInit() {
        this.users = this._userServices.getUsers();

        this.invitedUsers = this._userServices.getInvitedUser();
        if (this.invitedUsers == null) {
            localStorage.setItem('InvitedUsers', JSON.stringify([]));
        }

        this.inviteUserForm = this.fb.group({
            email: ['', [Validators.required, Validators.email]],
            name: [
                '',
                [
                    Validators.required,
                    Validators.pattern(/^(?! ).*[^ ]$/),
                    ,
                    validateName,
                ],
            ],
        });

        this.getData(this.invitedUsers);
    }

    getData(value) {
        this.dataSource = new MatTableDataSource<any>(this.invitedUsers);

        this.ngAfterViewInit();
    }

    ngAfterViewInit() {
        this.dataSource.paginator = this.paginator;
        this.dataSource.sort = this.sort;
    }

    existingUser = (value) => {
        this.filteredUser = this.invitedUsers.filter((user) => {
            return user.email == value.email;
        });
    };

    InviteUser = (value) => {
        this.existingUser(value);

        if (this.filteredUser.length <= 0 || this.filteredUser == undefined) {
            // console.log({ ...value, status: 'Invited' });
            this.invitedUsers.push({ ...value, status: 'Invited' });
            localStorage.setItem(
                'InvitedUsers',
                JSON.stringify(this.invitedUsers)
            );
            this._toastr.success('Successfully', 'Sent Invitation');

            this.router.navigate(['/user-manage']);
        } else {
            this._toastr.warning('Invited', 'User Already');
            return;
        }
    };

    onSubmit = () => {
        if (this.inviteUserForm.invalid) {
            return;
        } else {
            const dialogRef = this._fuseConfirmationService.open({
                title: 'Invite User',
                message: 'Are you sure to Invite a New User ?',
                icon: {
                    show: true,
                    name: 'heroicons_outline:exclamation',
                    color: 'primary',
                },
                actions: {
                    confirm: {
                        show: true,
                        label: 'Yes',
                        color: 'primary',
                    },
                    cancel: {
                        show: true,
                        label: 'No',
                    },
                },
                dismissible: true,
            });
            dialogRef.afterClosed().subscribe((result) => {
                if (result == 'confirmed') {
                    this.InviteUser(this.inviteUserForm.value);

                    // this.router.navigate(['/user-manage']);
                }
            });
        }
    };

    cancelInvite = (i) => {
        const dialogRef = this._fuseConfirmationService.open({
            title: 'Cancel Invitation',
            message: 'Are you sure to Cancel the Invitation ?',
            icon: {
                show: true,
                name: 'heroicons_outline:exclamation',
                color: 'warn',
            },
            actions: {
                confirm: {
                    show: true,
                    label: 'Yes',
                    color: 'warn',
                },
                cancel: {
                    show: true,
                    label: 'No',
                },
            },
            dismissible: true,
        });
        dialogRef.afterClosed().subscribe((result) => {
            if (result == 'confirmed') {
                this.filterStatus = this.invitedUsers[i];
                this.updatedStatus = {
                    ...this.filterStatus,
                    status: 'Cancelled',
                };
                this.invitedUsers.splice(i, 1, this.updatedStatus);
                localStorage.setItem(
                    'InvitedUsers',
                    JSON.stringify(this.invitedUsers)
                );
                this._toastr.success('Successfully', 'Cancelled Invitation');
                this.router.navigate(['/user-manage']);
            }
        });
    };

    /** Announce the change in sort state for assistive technology. */
    announceSortChange(sortState: Sort) {
        // This example uses English messages. If your application supports
        // multiple language, you would internationalize these strings.
        // Furthermore, you can customize the message to add additional
        // details about the values being sorted.
        if (sortState.direction) {
            console.log(sortState.direction);

            this._liveAnnouncer.announce(`Sorted ${sortState.direction}ending`);
        } else {
            this._liveAnnouncer.announce('Sorting cleared');
        }
    }
}

When I Change to Next Page the Index Number Starting from 1 But Actually I Want to Continue the Index Number from the Previous Page

I Have Tried a lot of Methods But Nothing Works.

1 Answers1

0

I imagine you get the paginator using

@ViewChild(MatPaginator) paginator: MatPaginator; //<--see the name of the variable

You need know that the "count" is

{{1+i+(paginator?.pageIndex||0)*(paginator?.pageSize||0)}}

NOTE: I know that use "paginator?.prop||0" it's looks like few strange. It's only to work with strict mode. we can also use a template refrence variable (be carefull to have a name different that the variable in Viewchild)

<mat-paginator #pag ...>
</mat-paginator>

And use simply

{{1+i+(pag.pageIndex*pag.pageSize)}}
Eliseo
  • 50,109
  • 4
  • 29
  • 67