How to refresh datagrid programmatically

I have a grid that I want to refresh after a record insert into DB. Add data to DB is working correctly. But I'm trying to use grid.refresh() method and is not working (the UI is not updated). 

<ejs-grid #grdLive [dataSource]='_data' (queryCellInfo)='queryCellInfo($event)' [allowSorting]="true" [sortSettings]="sortOptions">
        <e-columns>
            <e-column field='id' headerText='Live ID' textAlign='Right' width=90></e-column>
            <e-column field='titulo' headerText='Título' width=120></e-column>
            <e-column field='dataLive' headerText='Data da Live' type="Date" textAlign='Right' width=90 format='dd/MM/yyyy' ></e-column>
            <e-column columnName="diaSemana" headerText='Dia da Semana' textAlign='Right' width=90></e-column>
            <e-column field='observacoes' headerText='Observações' textAlign='Right' width=120></e-column>            
        </e-columns>
    </ejs-grid>
<button ejs-button type="button" cssClass="e-primary" (click)="Salvar()">Salvar</button>


@ViewChild('grdLive') public grdLive: any;
public _data: Object[] = [];
constructor(private service: AbrechozeiraApiService) {    
    this.service.getLiveList().subscribe(data =>{      
      this._data = data;      
    });
  }

Salvar(){
       
    const live = {
      titulo: this.titulo,
      observacoes: this.observacoes,
      dataLive: this.dataLive,
      dataAlteracao: this.dataAlteracao,
      usuarioModificacaoId: this.usuarioModificacaoId
    };
   
    console.log(live);
   
    this.service.addLive(live).subscribe(response => {
      console.log(response);
      this.toastElement.show({title: 'Info Sistema', content: 'Tudo certo! Informação gravada.'});
      this.limparCampos();      
    }, error => {
      this.toastElement.show({title: 'Info Sistema', content: 'Erro ao gravar informação.'});
      console.log(error);
    });    
   
    this.GridReload();
  }

GridReload(){
    console.log("entrei o gridReload");
   
    this.service.getLiveList().subscribe(data =>{      
      var gridObj = this.grdLive;    
      gridObj.dataSource = data;
      gridObj.refresh();    
      console.log("passei pelo refresh");
    });        
  }






3 Replies

JS Johnson Soundararajan S Syncfusion Team May 27, 2024 04:43 PM UTC

Hi Eduardo Rocha,
 

We understand that you would like to refresh the datagrid programmatically after adding the data to the database. We suggest that you can refresh the grid using the freezeRefresh method instead of refresh method.
 

If you are still experiencing the issue, kindly provide the following details:


  1. Could you provide more details about the data format returned from this.service.getLiveList().subscribe?
  2. Please share your complete grid rendering code, including the associated event (such as the queryCellInfo event).
  3. Could you provide a simple sample that replicates the issue and a video demonstration of the problem for better understanding and prompt resolution?


The above-requested details will be very helpful for us to validate the reported query at our end and provide the solution as early as possible.


Regards,

Johnson Soundararajan S




ER Eduardo Rocha May 28, 2024 12:25 PM UTC

Thanks for your suggestion Johnson, but it did not fix the problem.


I will provide what you have requested.


cadastro.component.html

<h1 style="text-align: center;">Gestão</h1>
<div>
    <label class="label">ID:</label>
    <label #liveID class="label" style="font-weight: bold;">00</label><br>
    <label for="#autoInput" class="label">Título</label><br>
    <input #autoInput type="text" name="txtTituloLive" [(ngModel)]="titulo"
    class="e-input"        
    placeholder="Insira o título da live"/><br>
    <label for="#autoInput" class="label">Data</label><br>
   
    <input #autoInput class="e-input" name='TxtDtLive' type="text"
    nbInput type="date"  placeholder="Insira a data da live" [(ngModel)]="dataLive"/>  <br>
    <label for="#autoInput" class="label">Observações</label><br>
    <ejs-textarea floatLabelType="Auto" cssClass="e-filled" [(ngModel)]="observacoes" placeholder=""></ejs-textarea>  <br><br>  
   
    <button ejs-button type="button" cssClass="e-primary" (click)="Salvar()">Salvar</button>
    <button ejs-button type="button" cssClass="e-primary" (click)="Refresh()">Refresh</button>
   
    <br><br>

    <!-- Grid de gestão de lives -->
    <ejs-grid #grdLive [dataSource]='_data' (queryCellInfo)='queryCellInfo($event)' [allowSorting]="true" [sortSettings]="sortOptions">
        <e-columns>
            <e-column field='id' headerText='Live ID' textAlign='Right' width=90></e-column>
            <e-column field='titulo' headerText='Título' width=120></e-column>
            <e-column field='dataLive' headerText='Data da Live' type="Date" textAlign='Right' width=90 format='dd/MM/yyyy' ></e-column>
            <e-column columnName="diaSemana" headerText='Dia da Semana' textAlign='Right' width=90></e-column>
            <e-column field='observacoes' headerText='Observações' textAlign='Right' width=120></e-column>            
        </e-columns>
    </ejs-grid>
</div>    
<ejs-toast #toastElement></ejs-toast>



cadastro.component.ts

import { Component, OnInit, ViewChild } from '@angular/core';
import { FormsModule } from '@angular/forms';

import { ButtonModule } from '@syncfusion/ej2-angular-buttons';
import { TextAreaModule } from '@syncfusion/ej2-angular-inputs';
import { ToastModule } from '@syncfusion/ej2-angular-notifications';
import { GridModule, PageSettingsModel, GroupSettingsModel } from '@syncfusion/ej2-angular-grids';

import { AbrechozeiraApiService } from '../../../abrechozeira-api.service';

@Component({
  selector: 'app-live',
  standalone: true,
  imports: [ButtonModule, TextAreaModule, ToastModule, FormsModule, GridModule],
  templateUrl: './cadastro.component.html',
  styleUrl: './cadastro.component.css'
})
export class CadastroComponent implements OnInit{
  @ViewChild('toastElement') public toastElement: any;
  @ViewChild('grdLive') public grdLive: any;
 
  titulo: string = '';
  dataLive: Date = new Date();
  observacoes: string = '';    
  dataAlteracao: Date = new Date();
  usuarioModificacaoId: number = 1;
 
 
  public _data: Object[] = [];
  public pageOptions?: PageSettingsModel;
  public groupOptions: GroupSettingsModel = {
    //showDropArea: false,
    //columns: ['precoCusto']
  };
  public sortOptions?: object;
 
 
  constructor(private service: AbrechozeiraApiService) {    
    this.service.getLiveList().subscribe(data =>{      
      this._data = data;      
    });
  }
 
  ngOnInit(): void {    
    this.pageOptions = { pageSize: 50 };
    this.sortOptions = { columns: [{ field: 'id', direction: 'Descending' }] };
  }
 
  queryCellInfo(args: any) {    
    if(args.column.headerText === 'Dia da Semana') {
      if(args.data.dataLive != '' && args.data.dataLive != null && args.data.dataLive != undefined){
        args.cell.innerText = new Date(args.data.dataLive).toLocaleString("pt-br", { weekday: "long" });
      }
    }
  }
 
  Salvar(){
   
    const live = {
      titulo: this.titulo,
      observacoes: this.observacoes,
      dataLive: this.dataLive,
      dataAlteracao: this.dataAlteracao,
      usuarioModificacaoId: this.usuarioModificacaoId
    };
   
    console.log(live);
   
    this.service.addLive(live).subscribe(response => {
      console.log(response);
      this.toastElement.show({title: 'Info Sistema', content: 'Tudo certo! Informação gravada.'});
      this.limparCampos();      
    }, error => {
      this.toastElement.show({title: 'Info Sistema', content: 'Erro ao gravar informação.'});
      console.log(error);
    });    
   
    this.GridReload();
  }
 
  limparCampos(){
    this.titulo = '';
    this.observacoes = '';
    this.dataLive = new Date();
    this.dataAlteracao = new Date();
    this.usuarioModificacaoId =  0;
  }
 
  GridReload(){
    console.log("entrei o gridReload");
   
    this.service.getLiveList().subscribe(data =>{      
      var gridObj = this.grdLive;    
      gridObj.dataSource = data;
      gridObj.freezeRefresh();    
      console.log("passei pelo refresh");
    });        
  }
 
  Refresh(){
    var gridObj = this.grdLive;  
    gridObj.freezeRefresh();
  }
}


abrechozeira-api.service.ts

import  {HttpClient}  from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
   
@Injectable()
export class AbrechozeiraApiService {

  //readonly abrechozeiraAPIUrl = "http://api.abrechozeira.kinghost.net/api";
  readonly abrechozeiraAPIUrl = "https://localhost:7194/api";
  constructor(private http:HttpClient) { }

  // Tarefas
  addTarefa(data:any){
    return this.http.post(this.abrechozeiraAPIUrl + '/tarefas', data)
  }

  updateTarefa(id:number|string, data:any){
    return this.http.put(this.abrechozeiraAPIUrl + `/tarefas/${id}`, data)
  }

  deleteTarefa(id:number|string){
    return this.http.delete(this.abrechozeiraAPIUrl + `/tarefas/${id}`)
  }

  // TarefaTipos
  getTarefaTiposList():Observable<any[]>{
    return this.http.get<any>(this.abrechozeiraAPIUrl + '/tarefatipos');
  }

  addTarefaTipos(data:any){
    return this.http.post(this.abrechozeiraAPIUrl + '/tarefatipos', data)
  }

  updateTarefaTipos(id:number|string, data:any){
    return this.http.put(this.abrechozeiraAPIUrl + `/tarefatipos/${id}`, data)
  }

  deleteTarefaTipos(id:number|string){
    return this.http.delete(this.abrechozeiraAPIUrl + `/tarefatipos/${id}`)
  }

  // Status
  getStatusList():Observable<any[]>{
    return this.http.get<any>(this.abrechozeiraAPIUrl + '/status');
  }

  addStatus(data:any){
    return this.http.post(this.abrechozeiraAPIUrl + '/status', data)
  }

  updateStatus(id:number|string, data:any){
    return this.http.put(this.abrechozeiraAPIUrl + `/status/${id}`, data)
  }

  deleteStatus(id:number|string){
    return this.http.delete(this.abrechozeiraAPIUrl + `/status/${id}`)
  }

  // Vendas
  getVendasCompleta():Observable<any[]>{    
    return this.http.get<any>(this.abrechozeiraAPIUrl + '/Vendas/GetVendasCompleta');
  }

  getVendas():Observable<any[]>{    
    return this.http.get<any>(this.abrechozeiraAPIUrl + '/Vendas');
  }

  addVendas(data:any){
    return this.http.post(this.abrechozeiraAPIUrl + '/Vendas', data)
  }

  updateVendas(id:number|string, data:any){
    return this.http.put(this.abrechozeiraAPIUrl + `/Vendas/${id}`, data)
  }

  deleteVendas(id:number|string){
    return this.http.delete(this.abrechozeiraAPIUrl + `/Vendas/${id}`)
  }

  // Pessoa
  getPessoa():Observable<any[]>{    
    return this.http.get<any>(this.abrechozeiraAPIUrl + '/Pessoas');
  }

  public async getPessoaPorNick(nickName: string):Promise<any>{    
    return await this.http.get<any>(this.abrechozeiraAPIUrl + `/Pessoas/GetPessoaPorNick?nickName=${nickName}`).pipe().toPromise();
  }

  public async isClienteExistente(nickName: string):Promise<any>{
    console.log('isClienteExistente início' +  nickName);
    try {
      this.http.get<any>(this.abrechozeiraAPIUrl + `/Pessoas/GetPessoaPorNick?nickName=${nickName}`).pipe().toPromise().then(data =>{
        if(data != null){
          console.log('data não é nula');
          if(data.id == 0){
            console.log('id == 0');
            return false;
          }
          else{
            console.log('id != 0');
            return true;
          }
        }else{
          return false;
        }
      });
    } catch (error) {
      return false;
    }    
  }

  addPessoas(data:any){
    return this.http.post(this.abrechozeiraAPIUrl + '/Pessoas', data);
  }

  updatePessoas(id:number|string, data:any){
    return this.http.put(this.abrechozeiraAPIUrl + `/Pessoas/${id}`, data)
  }

  deletePessoas(id:number|string){
    return this.http.delete(this.abrechozeiraAPIUrl + `/Pessoas/${id}`)
  }

  // Produto
  getProdutoList():Observable<any[]>{    
    return this.http.get<any>(this.abrechozeiraAPIUrl + '/Produtos');
  }

  public async getProduto(id:number|string):Promise<any>{    
    return await this.http.get<any>(this.abrechozeiraAPIUrl + `/Produtos/${id}`).pipe().toPromise();
  }
  getProdutoListCompleto():Observable<any[]>{    
    return this.http.get<any>(this.abrechozeiraAPIUrl + '/Produtos/GetProdutosCompleto');
  }

  public async getProdutoPorDescricao(descricao: string):Promise<any>{    
    return await this.http.get<any>(this.abrechozeiraAPIUrl + `/Pessoas/GetProdutoPorDescricao?descricao=${descricao}`).pipe().toPromise();
  }

  public async isProdutoExistentePorCodigoEstoque(codigoEstoque:number|string):Promise<Boolean>{    
     try {
      return await this.http.get<any>(this.abrechozeiraAPIUrl + `/Produtos/ProdutoExistsByCodigoEstoque?codigoEstoque=${codigoEstoque}`).pipe().toPromise();
    } catch (error) {
      return false;
    }
  }

  addProdutos(data:any){
    console.log('entrei no add produto ' + this.abrechozeiraAPIUrl);
    return this.http.post(this.abrechozeiraAPIUrl + '/Produtos', data)
  }

  updateProdutos(id:number|string, data:any){
    return this.http.put(this.abrechozeiraAPIUrl + `/Produtos/${id}`, data)
  }

  deleteProdutos(id:number|string){
    return this.http.delete(this.abrechozeiraAPIUrl + `/Produtos/${id}`)
  }

  // Live  
  getLiveList():Observable<any[]>{
    return this.http.get<any>(this.abrechozeiraAPIUrl + '/lives');
  }

  addLive(data:any){
    return this.http.post(this.abrechozeiraAPIUrl + '/lives', data)
  }

  updateLive(id:number|string, data:any){
    return this.http.put(this.abrechozeiraAPIUrl + `/lives/${id}`, data)
  }

  deleteLive(id:number|string){
    return this.http.delete(this.abrechozeiraAPIUrl + `/lives/${id}`)
  }

}


If we can't fix with this, I will try to provide vídeo and a sample.


Thanks in advance,


Regards.


Ed



JS Johnson Soundararajan S Syncfusion Team June 3, 2024 11:36 AM UTC

Hi Eduardo Rocha,

Thank you for your patience.


We recommend utilizing the changeDataSource method to modify the datasource, which will automatically refresh the grid without the need for manual refreshing. Additionally, please verify if the updated data has been set in the GridReload method.

Please refer to the below API link for more information.

API link : Angular Grid API component - Syncfusion
 

If you are still experiencing the issue, kindly provide the following details:
 

  1. Could you provide a simple sample that replicates the issue.
  2. Share us video demonstration of the problem for better understanding and prompt resolution?
  3. Please provide the current Syncfusion package version which you are using in your application.


The above-requested details will be very helpful for us to validate the reported query at our end and provide the solution as early as possible.


Regards,

Johnson Soundararajan S


Loader.
Up arrow icon