Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I display a component while content loads? - Angular2+

Is it possible to load a component in place of loading... between <app-root> within the index.html of an Angular project?

When the Angular app is loading, if the connection is slow etc while the page loads, whatever is displayed between the <app-root></app-root> tags within the index.html file will be displayed on the screen.

I am wanting to place a spinner at the point such that it will look like something is happening in the background rather than have an blank white screen.

Here is the code for the spinner:

.lds-ring {
  display: inline-block;
  position: relative;
  width: 64px;
  height: 64px;
}
.lds-ring div {
  box-sizing: border-box;
  display: block;
  position: absolute;
  width: 51px;
  height: 51px;
  margin: 6px;
  border: 6px solid var(--pa-red);
  border-radius: 50%;
  animation: lds-ring 1.2s cubic-bezier(0.5, 0, 0.5, 1) infinite;
  border-color: var(--pa-red) transparent transparent transparent;
}
.lds-ring div:nth-child(1) {
  animation-delay: -0.45s;
}
.lds-ring div:nth-child(2) {
  animation-delay: -0.3s;
}
.lds-ring div:nth-child(3) {
  animation-delay: -0.15s;
}
@keyframes lds-ring {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

body {
  background: grey;
}
<div class="lds-ring">
  <div></div>
  <div></div>
  <div></div>
</div>

If I use this in the actual index.html file it does indeed work. However, If I have this as a component amongst my others and load it with the selector, ie:

<app-root>
   <app-spinner></app-spinner>
</app-root>

Nothing is displayed and the white screen is seen while waiting.

Is there a solution to this?

like image 613
physicsboy Avatar asked Nov 16 '25 18:11

physicsboy


1 Answers

There is no solution, because the reason the loading takes long is because it's loading the app module. The parsing of the template is done in here, so what you want, is just not possible. Angular also ignores anything inside the app-root tag.

The only way to do it is just plain html and css inside the index.html, or perhaps have a look at Server Side Rendering.

You can also try to create a sort of app shell which loads really fast, and have a spinner component loading in between.

Or create two different angular applications, one that is just a spinner, and the other on the actual app. Your spinner will load first and be very quick, and gets replaced by the main app quickly, this is cute but not trivial at all, and will take quite some time to implement.

Sooo, I'm still sticking with my original answer, don't do that, and just use plain html and css to add a spinner. This is the quickest and most responsive. If you are worried about SEO, then you can have a look at SSR.

like image 152
Poul Kruijt Avatar answered Nov 19 '25 09:11

Poul Kruijt