Is there a way to refresh the ngFor render?

Is there a way to refresh or rerender the ngFor in a component (hello.component.ts)? I'm looking to display images or charts instead of text.

Check out this simple example for reference: Stackblitz

Here is a potential solution:

 public show = true;
 addData(data){
      this.data.push(data);
      this.reload();
    }
  reload() {
    this.show = false;
    setTimeout(() => this.show = true);
  }

Answer №1

Not completely certain if I grasp what you need, but one solution could be to utilize a simple ngIf and zero-timeout method to refresh the component's template:

@Component({
  selector: 'hello',
  template: `<div *ngIf="show">
... your template
</div>`
})
export class HelloComponent  {

  public show = true;

  // ... your code

  reload() {
    this.show = false;
    setTimeout(() => this.show = true);
  }

}

Simply call the reload function when you wish to "reload" your component. By changing the value of show to false and allowing for one event loop cycle (setTimeout), you essentially remove the inner template. Subsequently setting show back to true triggers the rendering of the inner template once more.


UPD. Additionally, you can prompt Angular to re-render specific data parts within your component's template by manually altering that data:

@Component({
  selector: 'hello',
  template: `...
<div *ngFor="let i of data">
  {{i}}...
</div>`
})
export class HelloComponent  {

  public data = [];

  // ... your code

  reloadData() {
    this.data = [...this.data];
  }

}

This allows you to solely "reload" the data array, causing NgFor to handle the re-rendering of its inner template automatically. When assigning a new value to this.data (using spread operator), you instruct Angular to reconstruct the sections of the template bound with data.

Answer №2

One of the challenges we faced was making Angular recognize changes and redraw accordingly.

Working alongside a colleague, we explored multiple approaches to tackle this issue, which primarily involved filtering data.

In your shared StackBlitz example, you employ various techniques. I focused on a specific aspect: modifying the array used by ngFor to render DOM elements.

Explore the ngFor drawing update mutation here.

I also encountered a similar problem with my coworker when attempting to filter a list based on an input value without triggering a redraw in Angular. Our workaround involved incorporating ngModel into the input field.

Discover how ngFor handles drawing updates with ngModel integration.

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

Leveraging property information for a dropdown field

In my index.tsx file, I am fetching data that I pass to the component FormOne. This allows me to access the data in FormOne using props.data const [data, setData] = useState([]); ... return ( ... <FormOne data={data} /> ); I am looking to ...

Differentiate between minimum and maximum values on ion-range sliders with discrete color options

I am currently working on customizing the theme of my ionic app, specifically trying to assign different colors to the min and max knobs on an ion-range component. At the moment, I am only able to apply a single HTML property called "color" to the selector ...

Tips for aligning the arrow of a dropdown menu option

When examining the code provided, I have noticed the clr-select-container with specific attributes as depicted. In the screenshot attached, it displays the clr-select-container. The issue that I am encountering is that the inverted arrow is positioned a f ...

Challenges with inferring return values in Typescript generics

I'm encountering an issue with TypeScript that I'm not sure if it's a bug or an unsupported feature. Here is a Minimal Viable Example (MVE) of the problem: interface ColumnOptions<R> { valueFormatter(params: R): string; valueGette ...

The specified module could not be located in the ngx-toastr library

I'm having trouble finding the solution... ERROR in ./node_modules/ngx-toastr/fesm5/ngx-toastr.js Module not detected: Error: Unable to locate '/Users/vasanthan/Mean projects/node_modules/@angular/animations' in '/Users/vasanthan/Mean ...

Error NG0304: The element 'mat-select' is not recognized in the template of the 'LoginPage' component

After creating a basic app, I decided to incorporate Angular Material into my project. The app in question is an Ionic 6 / Angular 14 app, however, I encountered an error while attempting to implement mat-select: https://i.sstatic.net/Quc53.png To addres ...

Which grid systems work well with Angular4, particularly for organizing and refining table data?

Experimented with using ag-grid as it seemed to be the most suitable option. In my package.json, I have the following dependencies: "ag-grid": "^18.1.2", "ag-grid-angular": "^14.0.0", "ag-grid-community": ...

No defined window.XMLHttpRequest

My node.js application was designed to parse the HTML AST and Typescript AST of angular2 in order to extract necessary data. In order to accomplish this, I needed to import @angular/compiler and subsequently @angular/core, which has a peerDependency of zo ...

Should the RxJS interval() function be employed to receive live server updates?

In my Angular application, I implemented this code to continuously check for updates. export class RealTimeComponent { products$:any; constructor(private service: ProductService){} ngOnInit(){ this.products$ = interval(5000) .pipe( ...

Implementing conditions in Angular2 router

Here are my current routes: const appRoutes: Routes = [ { path: 'alert/:id', component: AlertDetailComponent }, { path: 'alerts', component: AlertsComponent }, { path: 'dashboard', component: EriskDashboardComponent }, { pa ...

Tips for utilizing parameters within SQL Server

Hello everyone! I am new to SQL Server in Azure functions using Typescript. I am currently facing an issue while trying to update a row in the database using declared variables, particularly with VARCHAR types. Strangely, it works fine in the database tool ...

Tips for updating the front end with the status of a lengthy playwright test

In the node backend, I have defined a route for test progress using SSE (https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events). The URL initialization is happening on the frontend. Below is the code snippet from th ...

New feature in Chrome allows credit card suggestions to be displayed in the name input field

On one specific page of my angular app, I have an input field for a name that is showing credit card suggestions. When I disable the autofill for credit cards in Chrome settings, it then shows suggestions for names instead. However, on another page with ...

Determining when it is necessary to loop over a variable

I'm facing a situation where I have two different responses based on whether we need to loop over an object or just display a variable. My attempted solution involved using ng-if else, but unfortunately, it didn't work as expected. This is the ...

errors.ts:30 ERROR Error: Unhandled promise rejection: Error: No routes found for specified URL Segment: 'products,%20productId'

I'm in the process of learning Angular by following a tutorial on a website. You can find it here: https://angular.io/start/routing Everything is going smoothly so far, except for the section on routing. If I add 'products/1' to the end of ...

Converting an array of objects into a unified object and restructuring data types in TypeScript

A few days back, I posted a question regarding the transformation of an array of objects into a single object while preserving their types. Unfortunately, the simplified scenario I provided did not resolve my issue. In my situation, there are two classes: ...

Anticipate receiving a 'Type' returned by external library functions

I've recently started learning TypeScript and have encountered a situation where I need to assign a type to a variable that is returned from a third-party library function with its own type definition. For instance: import {omit} from 'lodash&ap ...

Is it possible to reset the attributes of a container's children using a renderer?

Within a container, there are dropdowns, multiple selects, and quantity selections. When a button is clicked, I aim to reset the state of the component. https://i.stack.imgur.com/TY5un.png <input #select type="checkbox" value="somevalue"/> The ...

When transitioning from the current step to the previous step in the mat-stepper component, how can we emphasize the horizontal line that separates them?

screenshot of my progress I have progressed from A3 to A2 step, but I need to add a horizontal line between them. How can I achieve this and is it possible to do so using CSS styles? ...

What is the process for installing both highcharts-angular and highcharts together?

UPDATE: Issue resolved - the problem was that the package.json file was read-only (refer to my answer). I have an Angular application (version 7) and I am attempting to integrate Highcharts. I am following the guidelines provided by highcharts-angular her ...