首页 > 解决方案 > 在加载第一个组件之前在 Angular 中显示预加载器

问题描述

我正在使用Angular 6

我的应用程序在加载组件之前需要几秒钟,而这段时间用于加载资源和验证用户。

当这一切发生时,我的应用程序显示一个空白页。

我想用一个预加载器替换那个丑陋的白页,直到所有后台进程完成为止。

为此,我在里面添加了一个 CSS 加载微调index.html

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>My App</title>
  <base href="/">

  <!-- Fonts and icons -->

</head>
<body>
  <app-root>
    <!-- Pre-loading spinner -->
    <!-- This code within the app-root will be wiped of once the child component is loaded -->
    <!-- This code will not even be shown in the source code once the child component is loaded -->
    <!-- We can put any code css/html/image/etc here -->

    <style>
      /** CSS here. Since it will be wiped totally, 'll not cause any impact to the core stylesheet.
    </style>

    Loading<span class="d">.</span><span class="d d-2">.</span><span class="d d-3">.</span>
  </app-root>
</body>
</html>

这会显示一个页面

在此处输入图像描述

但问题是这样的。第一个加载的组件是app.component.html,它具有以下内容

<router-outlet></router-outlet>

它进一步加载了另一个组件admin-layout-component.html的内容

<div class="wrapper">
  <div class="sidebar" data-color="red">
    <app-sidebar></app-sidebar>
  </div>
  <div class="main-panel">
    <app-navbar></app-navbar>
    <router-outlet></router-outlet>
    <app-footer></app-footer>
  </div>
</div>

加载app.component后,会删除index.html中的微调器内容并开始显示空白页面,直到加载admin-layout 。

我尝试在app.component.html的路由器插座中添加相同的样式代码,但是当加载组件时,内容与微调器一起添加,并且微调器不会从其他页面中删除。

app.component.html在加载仪表板页面之前,我如何才能显示微调器。

这是一个视频它是如何工作的:https ://youtu.be/RSlTi0EQHm4

标签: angularangular6

解决方案


根据 Sunil 的回答,我在 Angular 8 中得到了这个工作。我从 App 组件中隐藏了 loader 元素,该组件在任何其他组件之前初始化。所以不需要到处添加这个。

不建议使用ElementRef操作 DOM,因此我使用Renderer2代替。

索引.html:

<body class="theme-primary">
  <div id="loader">
    <style>
      .application-loading-container {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        height: 100vh;
      }

      .application-loading-box {
        width: 300px;
        margin: 5px;
        text-align: center;
      }
    </style>
    <div class="application-loading-container">
      <div class="application-loading-box"><h2>Loading...</h2></div>
    </div>
  </div>
  <app-root></app-root>
</body>

app.component.ts:

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})

export class AppComponent implements AfterViewInit {
  constructor(private renderer: Renderer2) {}

  ngAfterViewInit() {
    let loader = this.renderer.selectRootElement('#loader');
    this.renderer.setStyle(loader, 'display', 'none');
  }
}

推荐阅读