Home > Back-end >  How to update/reload search results once an item has been modified in Angular 10?
How to update/reload search results once an item has been modified in Angular 10?

Time:08-10

Can someone please let me know how to show updated search results in Angular 10?

Detailed Background: The application has some filters to refine search results and when the user clicks on 'Search' button, multiple results are displayed in a grid layout along with edit option. The user clicks on 'Edit' button to update a particular record. This edit button opens up a modal dialog where modifications can be made. Once the modal dialog is closed, the search results still display the previous data instead of updated data. I would like to know how to refresh the search results automatically(without having to click on 'Search' button again) once a particular record has been update? How can I achieve this functionality? Any help is greatly appreciated. Thank you so much in advance.

Note: In this case, the search component is the parent and edit modal dialog is a child component.

Regards SLS

CodePudding user response:

you can do two things here

  1. If you are connecting to backend database then fire the api again after updating data.
  2. Store the search result data in a service variable(Behaviour subject) and update that service variable when ever you are modifying your data.

CodePudding user response:

The correct approach is to call the APIs again to refresh search results as mentioned in the @Saptarshi answer.

However, another quick and dirty way to do this is to reload the search results component. In the parent component:

HTML:

<ng-container *ngIf="showSearchResults">
  <app-search-results></app-search-results>
</ng-container>

TS:

refreshSearchResults() {
  this.showSearchResults = false
  setTimeout(() => this.showSearchResults = true)
}

Then just call refreshSearchResults when you want to update search results. This code works because by making the *ngIf condition false for a split second and then reverting it to true, it recreates the app-search-results component, once again calling the constructor and ngOnInit where the initialisation code lives, thus essentially reloading the component with the latest data.

This is a quick win, not the best approach, but its good to know this option exists.

  • Related