Как обновить данные таблицы матов из Angular Material - PullRequest
0 голосов
/ 11 октября 2019

друзья, я получаю pokeapi, но, поскольку я могу обновить следующие данные на второй странице, они не работают в источнике данных, что я могу делать неправильно?

. 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

нумерация элементовне обновляется после нажатия второй страницы, я подключился с модальной, но я просто вижу индекс от 1 до 5 на всех страницах, почему это произошло? его просто передний конец

Ответы [ 3 ]

4 голосов
/ 11 октября 2019

Чтобы получить индекс для обновления для следующих страниц ... нам нужно сделать следующее:

([pageIndex] X [pageSize]) + ([rowIndex] + 1) ... что в нашем коде сводится к следующему:

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

вы можете проверить работоспособность stackblitz демо здесь

1 голос
/ 11 октября 2019

У меня была похожая проблема. Я решил эту проблему, всегда генерируя новый источник данных при обновлении данных. Но я не знаю, есть ли лучший способ решить эту проблему.

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';
    })
}
1 голос
/ 11 октября 2019

Вы используете index, чтобы показать id, который связан с *ngFor и дать индекс текущей строки, вы можете либо добавить его из компонента, либо вы можете использовать pageSize и currentPage для вычисления идентификатора, например

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

увидеть его в действии

демонстрация прикрепления идентификатора к вашим данным

...