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

Angular 4: Utilizing reactive forms for dynamic addition and removal of elements in a string array

I am looking for a way to modify a reactive form so that it can add and delete fields to a string array dynamically. Currently, I am using a FormArray but it adds the new items as objects rather than just simple strings in the array. Here is an example of ...

Utilize a variable within an HTML attribute

Currently utilizing Angular and I have the following HTML snippet <input onKeyDown="if(this.value.length==12 && event.keyCode!=8) return false;"/> Is there a way for me to incorporate the variable "myNum" instead of the ...

The error message "@graphql-eslint/eslint-plugin: problem with the "parserOptions.schema" configuration"

Our team is currently working on developing micro-services using NestJS with Typescript. Each of these services exposes a GraphQL schema, and to combine them into a single graph, we are utilizing a federation service built with NestJS as well. I recently ...

Retrieve the response status using a promise

There is a promise in my code that sometimes results in an error response (either 400 or 403, depending on the user). I am trying to handle this situation by catching the response and implementing a conditional logic to execute different functions based on ...

Developing a declaration for an unnamed function in a JavaScript file

module.exports = function (argument1, argument2) { return { myFunction } function myFunction () { ... } } What is the process for creating a TypeScript declaration file for this specific JavaScript file? ...

NextAuth credentials are undefined and authentication is malfunctioning in React

I encountered the following issue: https://i.sstatic.net/3VBoJ.png This is the code snippet that I am using: return ( <> {Object.values(providers).map((provider) => { if (provider.id === "credentials") { ret ...

Styling the pseudo element ::part() on an ion-modal can be customized based on certain conditions

Looking for a solution regarding an ion-modal with specific CSS settings? I previously had the following CSS: ion-modal::part(content) { width: 300px; height: 480px; } Now, I need to adjust the height based on conditions: if A, the height should be lo ...

Exploring Angular 4: Performing tests on a component containing another component

I am currently conducting testing on my Angular application: ng test Below is the content of my html file (page-not-found.component.html): <menu></menu> <div> <h4> ERROR 404 - PAGE NOT FOUND </h4> </div> Afte ...

Utilize Angular to transform items in a nested array into comma-delimited values prior to assigning them to a grid

Here is an excerpt from a JSON response retrieved from an API: { "totalCount": 2, "customAttributes": [ { "objectType": "OWNER", "atrributeId" ...

What are the best practices for handling context in Angular?

Currently, I am focused on enhancing our code base to improve readability and performance. Our approach involves a container component that loads all necessary data and passes it down to child components via Inputs. While this is generally considered good ...

Tips for managing the error message "The key 'myOptionalKey' is optional in the 'myObject' type but necessary in the '{...}' type"

Issue I'm currently working on making a sortable table using a sample table component from Material-UI. I encountered an error when I included an optional key in the Data object. It seems that the type definition in the getComparator function does no ...

Start up a server using Angular along with Node.js and Express framework

I am encountering an issue with configuring Express as a server in my Angular application. The app loads without any issues when accessing the HOME route, but when trying to access another route, I receive an error message: Cannot GET / This is how I hav ...

Ivy workspace encountered an error with Angular being undefined: <error>

Recently, I attempted to install Angular on my MacOS terminal by entering the command $ npm install -g @angular/cli Unfortunately, the installation kept failing and the terminal displayed an error message. Subsequently, I tried the command $ sudo npm inst ...

I need help figuring out how to showcase the following object in an Angular 5 HTML file

https://i.sstatic.net/XXm3W.png The console screenshot above shows an object with two values: users and tickers, each being an array of values. How can I display these values in an Angular 5 HTML template similar to the screenshot above? I attempted to ...

Angular's ExceptionHandler provides a straightforward approach to handling errors observed in the application

I am experiencing a challenge with Angular's ExceptionHandler not properly handling errors that occur from API calls. Despite my attempts to use the handleError method, the errors are not being caught as expected. I am uncertain of what steps need to ...

Guide on associating user IDs with user objects

I am currently working on adding a "pin this profile" functionality to my website. I have successfully gathered an array of user IDs for the profiles I want to pin, but I am facing difficulties with pushing these IDs to the top of the list of profiles. My ...

Flag is activated to retrieve the data from the @Input source

@Input() config= []; flag = false; I need to change the flag to true only when I receive data in the config from the @input. Where should I do this? The data in the config is delayed and I am unable to access it in ngOnInit but can get it in ngOnChanges. ...

Enhancing Sharepoint with NTLM Authentication

I require assistance in utilizing the NTLM (node.js) package. My aim is to update data on a sharepoint server using the NTML node.js library. I am seeking information about NTML. How do I use NTLM? How can I retrieve data from the sharepoint server? What ...

Troubleshooting: Issues with Angular 2's default routing system

My Angular 4 app's default route isn't functioning properly. Could it be conflicting with my express routes? Interestingly, the wildcard route seems to be working fine. I'm puzzled as to what the issue might be. Here are my Angular routes: ...

Creating an array in TypeScript is a versatile and powerful feature that

While I have some familiarity with TypeScript, there is one thing that continues to intrigue me. I understand the distinction between Array<string> and string[]. I am aware that these declarations can be used interchangeably, such as: export class S ...