Updating an Angular mat-table when the drawer is located in a separate component: A complete guide

The primary element contains tabs, component A, B, and so on.

My component_A comes with preloaded information, but it also includes a filter button. Additionally, there is a button that triggers a drawer from another component (the main component).

 toggleDrawer(): void {
    this.drawerService.toggleDrawer(); // Invoking the service to toggle the drawer
  }

Main component:

        <mat-drawer-container class="drawer-container" autosize>
      <div class="main-component-container">
        <div class="mat-tab-grp">
          <nav
            class="nav-bar"
            mat-tab-nav-bar
            #tabGroup
            mat-stretch-tabs
            color="accent"
          >
            <a
              mat-tab-link
              *ngFor="let link of navLinks"
              [routerLink]="link.link"
              routerLinkActive
              #rla="routerLinkActive"
              [active]="rla.isActive"
            >
              <mat-icon>{{ link.icon }}</mat-icon>
              {{ link.label }}
            </a>
          </nav>
          <div class="ng-temp">
            <router-outlet></router-outlet>
          </div>
        </div>
      </div>
    <mat-drawer
        #drawer
        class="example-sidenav mat-elevation-z2"
        mode="side"
        position="end"
      >
<form [formGroup]="filterGroup" class="filter-fields">
some codes
</form>
    </mat-drawer>
    </mat-drawer-container>

TypeScript file:

 this.drawerService.toggleDrawer$.subscribe(() => {
        this.drawer.toggle(); // Toggling the drawer
      });

Moreover, there is a button for data retrieval

submitForm() {
this.dataService
        .fetchData(someParameters)
        .subscribe(
          (response) => {
              this.drawer.close(); //closing the drawer and updating the mat-table in component A.
            }
}

In the dataService:

....this.dataSourceSubject.next(tmp_table);

Once the drawer closes and the toggleDrawer() process completes, I wish for the mat-table to refresh as well. Currently, the table only updates when switching to other tabs, as component A resides within a mat-tab. Reloading the page is not an option since the preloaded data will be fetched again. Therefore, I am solely focused on updating the table.

https://i.sstatic.net/ctbSZsgY.png

Answer №1

I believe the issue lies in how the BehaviourSubject is handling data, specifically that it should emit the most recent data from the API call rather than previous data.

fetchData(someParameters): Observable<any[]> { 
    return this.service.GetData(enc_param).pipe( 
      map((response: any) => { 
        this.dataSourceSubject.next(response); // <- updated here!
        return tmp_ta 
      })
    );
}

Another possibility is that the problem could be related to how the mat-table and component A are receiving data from your BehaviorSubject.


Using Async Pipe

Ensure that in your service, there is an observable of the BehaviorSubject.

dataSourceSubject: BehaviorSubject<any> = new BehaviorSubject<any>([]);
dataSourceObservable$!: Observable<any>;

constructor() {
  this.dataSourceObservable$ = this.dataSourceSubject.asObservable();
}

Access this in the component using a getter to make it usable in HTML.

get dataSource$ () {
    return this.dataService.dataSourceObservable$;
}

When utilizing this property, remember to use the async pipe.

<table mat-table [dataSource]="dataSource$ | async" class="mat-elevation-z8">

Direct Binding

Follow the same approach as above, but subscribe to get the data and pass it to the mat-table.

ngOnInit() {
    this.sub.add(
       this.dataService.dataSourceObservable$.subscribe((data: any) => {
         this.data = data;
       })
    );
}

ngOnDestroy() {
    this.sub.unsubscribe();
}

Finally, when directly using this property.

<table mat-table [dataSource]="data" class="mat-elevation-z8">

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

Guide on achieving horizontal scrolling in Ionic 3

Check out this image I have a list of 10 names in an ion-scroll, but they are appearing on separate lines like paragraphs. Below is my HTML code: <ion-scroll scrollX="true" style="width:100vw; height:50px" > <ion-row class="headerChip"& ...

Ways to set a particular tab as active in Angular Material's Tab Component

Currently, I am exploring the Tabs Component from Angular Material (https://material.angular.io/components/tabs/overview) Upon initial page load, the first tab is automatically selected as default. I am curious to know how I can set a different tab to be ...

Styling Angular with FullCalendar - Personalized CSS Design

I'm struggling with custom styling using FullCalendar for Angular. Specifically, I need to change the background color of the 'More Events' Popover, but no matter what I attempt, my styles aren't taking effect. I've been trying to ...

Solving "ERROR TypeError: Cannot read property 'username' of undefined" in Angular

I encountered an error while trying to edit a user with Angular and Laravel. The issue arises when passing user data from the front-end to the back-end. Angular Material is being utilized in this project. The code in edit-user-dialog.component.ts: impo ...

How can I retrieve distance data from the Google Maps API within an Angular service?

I am currently working on implementing the JavaScript version of the Google Maps API in order to resolve a CORS issue that I encountered with the regular API. Specifically, I am looking to calculate the distance and time between two destinations. How can I ...

Assess the operational path resolver

In Angular, there has been a recent deprecation of class-based route resolvers in favor of functional resolvers. More information can be found in the documentation here. Are there any examples available for unit testing these functional resolvers? I have ...

Angular encountering a null value within a pre-existing nested object

Upon receiving a fully populated object from my server to my angular service, everything appears correct in Postman and when I use JSON.stringify in the Angular component. However, I encounter an issue when trying to access nested objects within the view. ...

Tips for transferring information from Angular 6 to Node.js

Having recently delved into Angular 6 for the first time, I find myself tasked with sending data to a Node.js server. The code snippet below illustrates my approach within an Angular function: import { Component, OnInit } from '@angular/core'; ...

When converting a .ts file to a .js file using the webpack command, lengthy comments are automatically appended at the end of

As a backend developer, I recently delved into UI technologies and experimented with converting TypeScript files (.ts) to JavaScript files (.js) using the webpack command. While the conversion works well, the generated .js file includes lengthy comments at ...

The sort icon in PrimeNG TurboTable is not displayed when the default sorting option is activated

When the default sorting option is enabled on PrimeNG's TurboTable, the sort icon is not initially visible upon loading. However, the column header is styled as intended and the data is sorted correctly. The sort icon only appears when I manually clic ...

Angular modal layout not behaving responsively

My current project involves working with Angular 7 and Bootstrap 4, where I utilize PSPDFKit to open PDF files in a viewer placed within a modal. One issue that I've encountered is that the modal does not adapt responsively to different screen sizes. ...

Nested interfaces can utilize sum types

An example showcasing the use of sum types: interface Cash { amount: number, type: 'cash' } interface Card { amount: number, type: 'card', cardNumber: string } type Payment = Cash | Card const displayPayment = (payment: Pay ...

Issue with event.stopPropagation() in Angular 6 directive when using a template-driven form that already takes event.data

I am currently developing a citizenNumber component for use in forms. This component implements ControlValueAccessor to work with ngModel. export class CitizenNumberComponent implements ControlValueAccessor { private _value: string; @Input() place ...

Leveraging animations in Angular2 that are defined outside of a component

I've recently put together a basic component @Component({ selector: 'saved-overlay', templateUrl: './saved-overlay.html', exportAs: 'saved-overlay', animations: [ trigger('inOut', [ transition ...

Is there a way to change the data type of all parameters in a function to a specific type?

I recently created a clamp function to restrict values within a specified range. (I'm sure most of you are familiar with what a clamp function does) Here is the function I came up with (using TS) function clamp(value: number, min: number, max: number ...

List with pulldown options

I am trying to implement a drop-down list with bullets using Angular 2, JavaScript, and CSS. Although I have managed to create the drop-down list, I am facing difficulty in adding bullets to the list items. Unfortunately, I have found that jQuery and Boot ...

Ways to ensure the React prop type matches the value provided when using typescript?

Within my List component, there are 2 props that it takes in: items = an array of items component = a react component The main function of the List component is to iterate over the items and display each item using the specified component. // List ...

Tips for resolving the "Page Not Found" error in your NextJs application

I am organizing my files in the following structure src/ ├── app/ │ ├── pages/ │ │ ├── authentication/ │ │ │ ├── SignUp/ │ │ │ │ └── page.tsx │ │ │ └── SignIn/ │ ...

What is the best way to expand all nested mat-expansion-panels in Angular?

Is there a way to open all nested mat-expansion-panel tabs? Currently, it only opens the first panel in nested mat-expansion-panel. openAllTab1() { this.accordion.openAll(); } Check out the stackblitz link here ...

The parameter 'EventTypes' cannot be assigned to a type of string

I am working on enhancing the functionality of the function provided below by adding types to it, clickEvent(event:Event) { this.event = event } The HTML Code: <a [href]="href" [target]="target" (click)="clickEvent('text')"></ ...