Gerardo Bautista
Gerardo Bautista

Reputation: 891

How update mat-table data from Angular Material

I'm getting the pokeapi but since I can refresh the following data on the second page, it doesn't work in the dataSource, what might I be doing wrong ?

.ts

import { Component, OnInit, OnDestroy, ViewChild } from '@angular/core';
import { Pokemoni } from '../models/pokemon.model';
import { PokeService } from './poke.service';
import { MatPaginator, MatTableDataSource, MatDialog, PageEvent} from '@angular/material';
import { SuperModalComponent } from './supermodal/supermodal.component';
@Component({
  selector: 'app-pokelista',
  templateUrl: './pokelista.component.html',
  styleUrls: ['./pokelista.component.scss']
})

export class PokelistaComponent implements OnInit, OnDestroy {
  dataSource = new MatTableDataSource<Pokemoni>(); // arreglo de tipo Tabla/Pokemon
  cols: string[] = ['id', 'pokemon', 'icono', 'detalles']; // columnas tabla lista
  pokemon: Pokemoni[] = [];
  superball = '../../../assets/images/png/superball.png';
  indicePagina = [3, 5, 10];
  totalPoke: number;
  pokePorPagina = 5;
  paginaActual = 1;
  @ViewChild(MatPaginator, {static: true}) paginacion: MatPaginator;

  constructor(
    private pokeServicio: PokeService,
    public dlg: MatDialog
  ) {}
  ngOnInit() {
    this.dataSource.paginator = this.paginacion;
    this.dataSource.paginator._intl.itemsPerPageLabel = 'Pokémon por Pagina';
    this.getPo();
  }
  getPo() {
    this.pokeServicio.getP().subscribe( (res) => {
      this.pokemon = res.pokemon;
      this.totalPoke = this.pokemon.length;
      this.dataSource.data = this.pokemon;
      this.dataSource.paginator = this.paginacion;
      // setTimeout(() => {  });
    });
  }
  getPokeD(i: number) {
    const index = i + 1;
    this.pokeServicio.setPokeDetails(index);
    this.openPokemon();
  }

.html

<div class="container">
    <mat-card>
        <div class="filter">
            <mat-form-field>
                <input matInput type="text" (keyup)="makeFiltro($event.target.value)" placeholder="Filtro" />
            </mat-form-field>
            <button color="warn" mat-button>
            Ver Selección
            </button>
        </div>
        <div class="container">
            <table mat-table [dataSource]="dataSource">
                <ng-container matColumnDef="id">
                    <th mat-header-cell *matHeaderCellDef>ID</th>
                    <td mat-cell *matCellDef="let element; let i = index">{{ i + 1 }}</td>
                </ng-container>
                <ng-container matColumnDef="pokemon">
                    <th style="padding-right: 50px;" mat-header-cell *matHeaderCellDef>
                        Pokémon
                    </th>
                    <td style="padding-right: 50px;" mat-cell *matCellDef="let element">
                        <strong>{{ element.pokemon | titlecase }}</strong>
                    </td>
                </ng-container>
                <ng-container matColumnDef="icono">
                    <th style="padding-right: 50px;" mat-header-cell *matHeaderCellDef>
                        Icono
                    </th>
                    <td mat-cell *matCellDef="let element">
                        <img class="mobile-label" style="width: 45px;height:45px" [src]="element.icono" />
                    </td>
                </ng-container>
                <ng-container matColumnDef="detalles">
                    <th style="padding-right: 50px;" mat-header-cell *matHeaderCellDef>
                        Detalles
                    </th>
                    <td id="superball" style="padding-left: 50px;cursor: pointer;" mat-cell *matCellDef="let element; let i = index;">
                        <img (click)="getPokeD(i);$event.stopPropagation()" [src]="superball" />
                    </td>
                </ng-container>
                <mat-header-row *matHeaderRowDef="cols"></mat-header-row>
                <mat-row *matRowDef="let row; columns: cols"></mat-row>
            </table>
        </div>
    </mat-card>
    <mat-card>
        <mat-paginator #paginacion [pageSizeOptions]="indicePagina" (page)="onChangePagina($event)" [length]="totalPoke" [pageSize]="pokePorPagina"></mat-paginator>
    </mat-card>
</div>

enter image description here

The pagination of the items does not update after click second page, I have connected with a modal but just I see the index 1 to 5 in all pages, why did that happen? It's just front end.

Upvotes: 0

Views: 375

Answers (3)

JuNe
JuNe

Reputation: 1997

I had a similar issue. I solved it by always generating a new dataSource when I refresh data. But I don't know if there is a better way to solve this problem.

getPo() {
    this.pokeServicio.getP().subscribe( (res) => {
      this.pokemon = res.pokemon;
      this.totalPoke = this.pokemon.length;
      this.dataSource = new MatTableDataSource<Pokemoni>(this.pokemon);;
      this.dataSource.paginator = this.paginacion;
      this.dataSource.paginator._intl.itemsPerPageLabel = 'Pokémon por Pagina';
    })
}

Upvotes: 1

Rahul Gupta
Rahul Gupta

Reputation: 1041

To get the index to update for the next pages... we do like the following:

( [pageIndex] X [pageSize] ) + ( [rowIndex] + 1 )... which comes down to the following in our code:

<mat-table #table2 [dataSource]="dataSource2" matSort>
 <ng-container matColumnDef="description">
 <mat-header-cell *matHeaderCellDef mat-sort-header> Description </mat-header-cell>
    <mat-cell *matCellDef="let item; let j = index"> 
      {{ (j+1) + (myPaginator.pageIndex * myPaginator.pageSize) }} - 
      {{item.description}} </mat-cell>
  </ng-container>
 <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
    <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
</mat-table>
<mat-paginator #myPaginator [length]="25"
              [pageSize]="5"
              [pageSizeOptions]="[5, 10, 25, 100]">
</mat-paginator> 

you can check working stackblitz demo here

Upvotes: 4

jitender
jitender

Reputation: 10429

You are using index to show id which is associated with *ngFor and give index of current row you can either add it from component or you can use pageSize and currentPage to calculate id like

{{(currentPage*pageSize)+i+1}}

see it in action

demo attaching id to your data

Upvotes: 1

Related Questions