How to manually force a rerender of a component in Angular2?
Asked Answered
M

1

5

I am using ng Smarttable and change the datasource array via an event (the change is an id change of a value inside the array). The problem is that angular doesnt detect the changes and nothing happens UNTIL i hover over the page or click somewhere.

So the changes are correctly applied behind the scenes and angular "sees" these changes once i click somewhere.

So i could just manually click alot of times to see the chaning property, but this is not desired.

I tried:

  1. using ChangeDetectorRef inside the function where i change the array (markAsChanged & DetectChange)
  2. manually making a click event once the array is changed
  3. Using Immutability (this.data= [...this.data];)

Is it possible to have something like this?

this.renderer.refresh();

or use just a functionality of ng smartable?

EDIT: it looks like the problem was on my side. When you "refresh" the smarttable,you get a promise which only executes once the loading is finished.

I didnt used the promise. Putting the normal DetectChange() inside the promise made it work

Mchugh answered 18/3, 2019 at 10:22 Comment(6)
Have you tried immutability ? When you change the datasource for example you have a data array try writing this line in your event listener: this.data = [...this.data].Decal
Yes, its not workingMchugh
Can you post a snippet of your code here or on Stackblitz and tell us the current and desired behaviors?Linalool
unfortunately i dont think this is possible since its code from workMchugh
Have you tried the ng2-smarttable refresh method: github.com/akveo/ng2-smart-table/issues/109# or look at their documentationDecal
yes, but the problem was on my side. Look at the edit for the solutionMchugh
H
9

You can manually re-render using application ref.

Inject ApplicationRef to your component.

constructor(appRef: ApplicationRef) {}

Then call tick method whenever you want to re-render

appRef.tick();
Histrionic answered 18/3, 2019 at 10:40 Comment(3)
For an library specific solution, check on this thread. github.com/akveo/ng2-smart-table/issues/718Histrionic
@Mchugh great. But for the question you asked, how to do a manual re-rendering, this is the answer.Histrionic
This is brilliant! Nice and short. Thanks a lot!Reed

© 2022 - 2024 — McMap. All rights reserved.