Angular 14 + PrimeNG : Falha ao criar uma nova página em uma p-table paginada

7 respostas Resolvido
angular2algortimo
A

Bom dia pessoal, estou com problemas no meu algoritmo e não consigo identificar o erro
estou usando Angular 14 + PrimeNG, e ao gravar novos itens as linhas sao atualizadas normalmente, no entanto quando ultrapasso as 10 linhas por paginas a minha p-table não atualiza dinamicamente criando uma nova pagina, é preciso que eu de um refresh manualmente na pagina pra pagina 2 aparecer, segue abaixo minha tela HTML

<p-table #dt id="table-author" [value]="authors" [rows]="10" [rowsPerPageOptions]="[10,20,30]" [showCurrentPageReport]="true" [paginator]="true" [globalFilterFields]="['name']"
   [rowHover]="true" dataKey="id"
    currentPageReportTemplate="Exibindo de {first} a {last} de um total de {totalRecords}" [showCurrentPageReport]="true">
    <ng-template pTemplate="caption">
        <div class="flex flex-column md:flex-row md:justify-content-between md:align-items-center">
            <h5 class="m-0">Listagem de Autores</h5>
            <span class="block mt-2 mt-0 p-input-icon-left">
                <i class="pi pi-search"></i>
                <input pInputText type="text" (input)="onGlobalFilter(dt, $event)" placeholder="Pesquisar..."  class="w-full sm:w-auto"/>
            </span>
        </div>
    </ng-template>
    <ng-template pTemplate="header">
        <tr>
            <th pSortableColumn="authorId">Código<p-sortIcon field="authorId"></p-sortIcon></th>
            <th pSortableColumn="name">Nome<p-sortIcon field="name"></p-sortIcon></th>
            <th></th>
        </tr>
    </ng-template>
    <ng-template pTemplate="body" let-author>
        <tr>
            <td>{{author.authorId}}</td>
            <td>{{author.name}}</td>
            <td>
                <button pButton pRipple icon="pi pi-pencil" class="p-button-rounded p-button-primary mr-2" (click)="onEdit(author)"></button>
            </td>
        </tr>
    </ng-template>
    <ng-template pTemplate="summary">
        <div class="p-d-flex p-ai-center p-jc-between">
            Total de {{authors ? authors.length : 0 }} authors.
        </div>
    </ng-template>
</p-table>

7 Respostas

A

e esse é meu Compenent:

@Component({

selector: app-authors,

templateUrl: ./authors.component.html,

styleUrls: [./authors.component.scss],

})

export class AuthorsComponent implements OnInit {
author: Author;
authors: Author[] = [];
showLoading: boolean = true;
displayModalCadastro: boolean = false;

constructor(
    private authorsService: AuthorsService,
    private messageService: MessageService

) {
    this.author = {};

}

ngOnInit(): void {
    this.findAllAuthors();
}

findAllAuthors() {
    this.authorsService.findAll().subscribe(
        (dados) => {
            this.authors = dados;
            this.showLoading = false;
        },
        (error) => {
            this.showLoading = true;
            this.showToast('error', error);
        }
    );
}

onSubmit() {
    try {
        this.validationForm();
        this.authorsService
            .save(this.author)
            .subscribe((result: Author) => {

                if (this.author.authorId)
                    //update
                    this.authors[this.findIndexById(this.author.authorId)] = this.author;
                else
                    //create
                    console.log(this.authors.length)
                    this.authors.push(result);
                    console.log(this.authors.length)
            },
                error => {
                    this.showLoading = false;
                    this.showToast('warn', error);
                    this.authors = [];
                });

        this.authors = [...this.authors];
        this.displayModalCadastro = false;

    } catch (error) {
        this.showToast('warn', error);
    }
}

validationForm() {
    if (!this.author.name)
        throw new Error('O campo nome é obrigatório!');
}


private showToast(severity: string, detail: any) {

    this.messageService.clear();
    this.messageService.add({ severity: severity, detail: detail, life: 6000 });

}

findIndexById(authorId: number): number {

    let index = -1;
    for (let i = 0; i < this.authors.length; i++) {
        if (this.authors[i].authorId === authorId) {
            index = i;
            break;
        }
    }

    return index;
}

onEdit(author: Author) {
    this.showDialogCadastro();
    this.author = { ...author };
}

showDialogCadastro() {
    this.displayModalCadastro = true;
    this.author = {};
}

hideModalAddDialog() {
    this.displayModalCadastro = false;
    this.author = {};
}

onGlobalFilter(table: Table, event: Event) {
    table.filterGlobal((event.target as HTMLInputElement).value, 'contains');
}

}

A

fiz um video explicando o problema na tela :smiley:

L

Em vez de fazer push no array, tente usar o spread operator para adicionar o novo elemento:

this.authors= [...this.authors, result];

Isso deve fazer com que a referência do array mude e o componente seja forçado a ser atualizado.

A

Oi Lucas! obrigado! funcionou! mas acabei de ver que tenho outro problema, se eu editar um item, esse item fica duplicado, eu tenho que dar refresh na tela pra ele desaparecer, sabe o que pode ta ocorrendo?

tambem fiz um video demonstrando!

L

A função que salva é a mesma q edita?

A

sim!

o ‘if (this.author.authorId)’ é o que diferencia o que vai ser feito

A
Solucao aceita

ja deu certo lucas! chat gpt me ajudou kkk

if (this.author.authorId) {

const index = this.findIndexById(this.author.authorId);

const updatedAuthors = […this.authors];

updatedAuthors[index] = this.author;

this.authors = updatedAuthors;

}

else

//create

this.authors = […this.authors, result];

OBRIGADO!

Criado 1 de abril de 2023
Ultima resposta 1 de abr. de 2023
Respostas 7
Participantes 2