drbishop drbishop - 1 year ago 72
TypeScript Question

Stop reloading the whole content on route change

I have a route like the following:

, where it loads a different content for each
. However, every time I go to a different page, it reloads the entire content. I'd like to reload only the data coming from the API.


<li [routerLink]="['/page', 1]">Page 1</li>
<li [routerLink]="['/page', 2]">Page 2</li>
<li [routerLink]="['/page', 3]">Page 3</li>

<h1 *ngIf="data">{{data.name}}</h1>


export class DataComponent implements OnInit {

data: any;
error: any;

private route: ActivatedRoute,
private service: DataService
) {}

ngOnInit() {

getData() {
res => this.data = res,
error => this.error = error


If you go to this Plunker, you'll see the black rectangle blinks every time the route changes. Ideally, the black part would remain intact, only the data inside would change.

I also noticed this flickering behavior happens only if I'm using an HTTP call. If I'd have other things in that component, this wouldn't happen when changing routes.

Any ideas on how to solve this?

Answer Source

Your blinking occurs because when you navigate, DataComponent is destroyed and re-built, but it cannot be shown until new data arrives from the server because you block its display with *ngIf="data". On this plunker, I've added a 1 second delay to the server response to make the problem obvious. Note that only the DataComponent blinks. The rest of PagesComponent does not.

On this plunker, there is no visible blinking because the data is hard-coded so there is no wait for the server's response.

To alleviate to blinking, don't use *ngIf since that removes the element from the dom entirely. On this plunker, no blinking occurs even while we wait for data to arrive from the server.

Basically, as long as you want to hide the element while you wait for data, whenever the component is re-initialized and you wait for new data needs to be fetched, you will see blinking.