Angular: Refresh Mat-Table data following any changes

I'm currently working with a Mat-table that has expandable rows, each containing an update functionality for the data. While the POST and GET requests are functioning properly, I encounter an issue where I need to reload the page in order to see the updated data after performing an update operation. Even after using the renderRows() method of the mat-table following the UPDATE query execution, the refresh doesn't seem to work as expected. Below is a snippet of my code:

abc.service.ts

createExamCategory(options) {
    return this.http.post<{ message: string }>(this.url + '/createExamCategory', options);
}

getExamCategory():Observable<any> {
    return this.http.get<any>(this.url + '/getAllExamCategory');
}

abc.component.html

<table mat-table [dataSource]="dataSource" multiTemplateDataRows>
      <ng-container matColumnDef="{{column}}" *ngFor="let column of columnsToDisplay; index as i">
        <th mat-header-cell *matHeaderCellDef>
          {{column=='id'?'Id':column=='examCategoryName'?'Category':column=='isActive'?'Status':''}}
        </th>
        <td mat-cell *matCellDef="let element"> 
          <label [class.table-data]="column=='isActive'">{{element[column]}}</label>
          <label *ngIf="column=='isActive' && element[column]">Active</label>
          <label *ngIf="column=='isActive' && !element[column]">Inactive</label>
          <button mat-icon-button color="primary" *ngIf="column=='Action'" (click)="expandedElement = expandedElement === element ? null : element">
            <mat-icon fontSet="material-icons-outlined" (click)="onClick(element)">edit</mat-icon>
          </button>
        </td>
      </ng-container>
      <ng-container matColumnDef="expandedDetail">
        <td mat-cell *matCellDef="let element" [attr.colspan]="columnsToDisplay.length">
          <div class="example-element-detail" [@detailExpand]="element == expandedElement ? 'expanded' : 'collapsed'">
            <div class="example-element-description">
              <form [formGroup]="updateExamCategory" (ngSubmit)="updateExamCategoryForm()">
                <mat-form-field class="example-full-width create-fields">
                  <mat-label>Category</mat-label>
                  <input matInput formControlName="examCategoryName">
                </mat-form-field>
                <mat-slide-toggle formControlName="isActive">{{Status.value==true?'Active':'Inactive'}}</mat-slide-toggle>
                <button type="submit" mat-flat-button color="primary" style="display: inline;margin-left: 50px;">Update</button>
              </form>
            </div>
          </div>
        </td>
      </ng-container>
      <tr mat-header-row *matHeaderRowDef="columnsToDisplay"></tr>
      <tr mat-row *matRowDef="let element; columns: columnsToDisplay;" class="example-element-row" [class.example-expanded-row]="expandedElement === element"></tr>
      <tr mat-row *matRowDef="let row; columns: ['expandedDetail']" class="example-detail-row"></tr>
    </table>
    <mat-paginator [length]="100" [pageSize]="10" [pageSizeOptions]="[5, 10, 25, 100]" showFirstLastButtons></mat-paginator>

abc.component.ts

onClick(e) {
    this.updateExamCategory.controls['id'].setValue(e.id);
    this.updateExamCategory.controls['examCategoryName'].setValue(e.examCategoryName);
    this.updateExamCategory.controls['isActive'].setValue(e.isActive);
    this.change[0] = this.updateExamCategory.get('examCategoryName').value;
    this.change[1] = this.updateExamCategory.get('isActive').value;
}

get Status() {
    return this.updateExamCategory.get('isActive');
}

get examCatergory() {
    return this.updateExamCategory.get('examCategoryName');
}

updateExamCategoryForm() {
    if(this.change[0] == this.examCatergory.value && this.change[1] == this.Status.value) {
      return alert('Same Value cannot be updated');
    }
    this.adminCategory.createExamCategory(this.updateExamCategory.value).subscribe(reponse => {
      return console.log(reponse.message);
    });
}

getTableData() {
    this.columnsToDisplay = ['id', 'examCategoryName', 'isActive', 'Action'];
    this.adminCategory.getExamCategory().subscribe((reponse: any) => {
      this.ExamCategoryData = reponse.examCategoryList;
      this.dataSource = new MatTableDataSource(this.ExamCategoryData);
      this.dataSource.paginator = this.paginator;
    }, error => {
        console.log(error);
    });
}

ngOnInit() {
    this.getTableData();
}

This is the current state of my code. Any suggestions on what needs to be added or changed to resolve this issue?

Answer №1

Here is a potential solution for you:

updateExamCategoryForm() {
  if (this.change[0] == this.examCatergory.value && this.change[1] == this.Status.value) {
    return alert('Cannot update with same value');
  }
  this.adminCategory.createExamCategory(this.updateExamCategory.value)
  .subscribe(response => {

    // You have the option to reload data from the service or
    // add it to your current list and reset your dataSource

    // If the response matches the GET call response
    this.ExamCategoryData = response.examCategoryList;
    this.dataSource = new MatTableDataSource(this.ExamCategoryData);
    this.dataSource.paginator = this.paginator;
    return console.log(response.message);
  });
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Positioning Placeholder in Angular Material's mdInput

I am currently in the process of designing a Form for my website, but I am encountering an issue with the Input and its Placeholder. The implementation should be straightforward, resembling something similar to this. However, the Placeholder is appearing ...

Retrieve Json data from an external API in Angular by utilizing the HttpClient module

Being a novice in angular, I am experimenting with fetching data from an external API. Although I managed to retrieve the data successfully on the console, I encountered errors when attempting to display it on the screen. Below are the details of my setup: ...

Server Components can only receive plain objects and select built-ins from Client Components. Any classes or null prototypes will not be compatible

I am encountering an error when wrapping the App.ts with queryclientprovider: "Only plain objects, and a few built-ins, can be passed to Client Components from Server Components. Classes or null prototypes are not supported." Below is the code snippet from ...

Developing an exportable value service type in TypeScript for AngularJS

I have been working on creating a valuable service using typescript that involves a basic switch case statement based on values from the collection provided below [{ book_id: 1, year_published: 2000 }, { book_id: 2, year_publish ...

Executing a function in Angular 2 depending on the class assigned to a <div>

In my HTML code, I am using *ngFor to iterate through an array of messages. <div *ngFor="let message of messages; let i=index" [focused]="i === activeIndex;" [ngClass]="{'message-list-active': activeIndex === i }" (click)="onAddtoMessag ...

Ways to identify when an HTMLElement's size changes due to a percentage-based width setting

Currently, I am in the process of developing an Angular Component and have implemented the following CSS code: :host { display: block; width: 100%; } The main objective here is to ensure that the component remains as responsive as possible. However, ...

Disable the functionality of the device's back button to prevent it from going back to the

For my project, I utilize popups to display important information to the user. When a popup is displayed, how can I override the functionality of the device's back button so that instead of navigating to the previous route, it will close the popup? ...

Guide on Implementing jQuery Plugin with Vue, Webpack, and Typescript

I am currently exploring the integration of the jQuery Plugin Chosen into my vue.js/Webpack project with TypeScript. After some research, I discovered that it is recommended to encapsulate the plugin within a custom Vue component. To kick things off, I m ...

Using Angular to include more than two parameters in an HTTP GET request

Currently, I am developing an application that requires downloading a file upon clicking a button within a template. The screen displays multiple files, each with its own corresponding button. I need to send the index number of the array to Angular and pas ...

Is it possible for a d3 chart to render twice in one area if it's rendered in two different places?

When attempting to showcase two distinct d3 pie charts on my webpage within individual mat-cards, they both end up displaying in the svg tag of the first d3 chart in my code. This is what my code looks like: <section class="three"> <! ...

What are the reasons behind memory leaks and decreased rendering speed when I exit and then reopen a React component (specifically Material-Table)?

I have been working on a basic React example for learning purposes, and I incorporated the use of material-table in one of my components. However, I noticed that each time I change pages and reopen the component (unmount and mount), the rendering speed of ...

Ways to resolve the issue with the Argument of type 'Date[]' not matching the parameter type '(prevState: undefined) in React

I've encountered an issue while trying to construct my project. The error message reads as follows: Argument of type 'Date[]' is not assignable to parameter of type '(prevState: undefined) Here's the excerpt of the code in questio ...

Utilizing Express-WS app and TypeScript to manage sessions

I am currently working on setting up a node server using Typescript with the help of express and express-ws. My goal is to include Sessions in my application, so I have implemented express-session. Below you can find some pseudo code: import * as session ...

Can storing JWT in the windows object be considered a secure method for easy retrieval when required?

I have received an access token (JWT) in the URL. For example: . Is it secure to save this token in the window object? For instance: window.jwt = Token If so, how can it be utilized (extracting the JWT from the Window object and carrying out subsequent ...

Creating a reusable field for reactive forms in Angular: A step-by-step guide

I need assistance with creating a versatile field component for reactive forms, but I am facing challenges in retrieving the value from the custom-input element. <form [formGroup]="form" (ngSubmit)="submit()"> <custom-input i ...

Angular and Spring Boot integration with Apereo CAS application

For my current project, I am building an application with Angular6 for the frontend and spring boot for the backend. Initially, all APIs in my backend are open to everyone, accessible via URLs like localhost:8080/api/get_data from the frontend. However, I ...

Nuxt encountered an issue with Vue hydration: "Tried to hydrate existing markup, but the container is empty. Resorting to full mount instead."

I'm facing an issue while trying to integrate SSR into my project. I keep encountering this error/warning. How can I pinpoint the problem in my code? There are numerous components in my project, so I'm unsure if I should share all of my code, b ...

Guide to sending a HTTP POST request with parameters in typescript

I need assistance sending a POST request using parameters in the following format: http://127.0.0.1:9000/api?command={"command":"value","params":{"key":"value","key":"value","key":"value","key":value,}} I attempted to do this but encountered an issue: l ...

Ways to dynamically update a Vuetify 3 element's placeholder text?

Here is the code snippet from my component.vue file: <template> <v-text-field name="Foo" :label="$t('foo')" type="text" hint="This is a hint" persistent-hint >& ...

The specified object '[object Object]' is not compatible with NgFor, which only supports binding to iterable data types like Arrays

I have some code that is attempting to access objects within objects in a template. <table class="table table-striped"> <tr *ngFor="let response of response"> <td><b>ID</b><br>{{ response.us ...