I have a component that I need to re-render every time with different @input variables because I have some logic implemented in ngOnInit(). I am doing this by using following method in parent component with showSettings being used to hide and then show the component (with new inputs) after 100ms delay.
private _reloadSettings() {
this.showSettings = false;
let a = performance.now();
setTimeout(() => {
this.showSettings = true;
console.log(performance.now() - a);
}, 100);
}
Everything is working fine except that the re-render takes so much time than expected i.e. it should be around 100ms (or a little over) but actually I am getting like 8000ms to 10000ms,
and with each re-render it gets worst.
In other parts of your application, you are doing too much work.
We cannot solve your problem in this case. I would go about looking into angular change detection.
Other than that, I will show you few things to look for in your codebase:
You could switch from ChangeDetection.Default to ChangeDetection.OnPush. This may break parts of your app, but if you would fix those, you will get a big performance boost for all app-wide actions as setTimeout is.
In the example above, you are listening to service observable, it might be anything
constructor(myService) {
myService.data.subscribe(data => {
this.array = data.array;
});
}
The code above is bad, the subscription is never removed, meaning the browser cannot remove the component from memory AND the code inside subscribe method runs every time. It is fine in this case, but if you were to do some computation inside, it could get bad quickly.
You can fix it by:
myService.data.pipe(
take(1),
).subscribe(data => {
this.array = data.array;
});
this.array$ = myService.data.pipe(
map(data => data.array),
// Uncomment next line, if the observable is used multiple time
// shareReply({ ... }), //
)
Try using queueMicrotask instead of setTimeOut.
queueMicrotask(() => {
this.showSettings = true;
console.log(performance.now() - a);
});
SetTimeout is a macro task. The call back function provided in setTimeout will be loaded into the call back queue(aka MacroTaskQueue). It waits until the call stack is empty.
The micro task also has similar behavior. But, the microtask gets higher priority, and hence it runs prior to the macro task queue.