首页
/ NGX Progressbar 教程

NGX Progressbar 教程

2026-01-17 09:29:32作者:董斯意

1. 项目介绍

NGX Progressbar 是一个轻量级的 Angular 模块,用于在网页加载过程中展示进度条。该项目提供多种功能,包括对 Http 请求、路由事件的支持,以及创建多个独立的进度条实例。它允许自定义配置,如颜色、速度等,并与 Angular 应用程序无缝集成。

2. 项目快速启动

安装依赖

首先,你需要安装 ngx-progressbar 到你的 Angular 项目中:

npm install ngx-progressbar

引入模块

接着,在你的主模块(比如 app.module.ts)中导入所需模块:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { RouterModule } from '@angular/router';
import { NgProgressModule, NgProgressHttpModule } from 'ngx-progressbar';

import { AppComponent } from './app.component';

@NgModule({
  imports: [
    BrowserModule,
    HttpClientModule,
    RouterModule.forRoot([]),
    NgProgressModule.forRoot(), // 全局配置
    NgProgressHttpModule, // 针对 Http 请求的自动跟踪
  ],
  declarations: [AppComponent],
  bootstrap: [AppComponent]
})
export class AppModule {}

使用组件

在你的组件模板中添加 <ng-progress> 标签:

<ng-progress></ng-progress>

自动跟踪 HTTP 请求

如果你正在使用 Angular 的 HttpClient,NgProgressHttpModule 可以自动追踪请求并更新进度条:

import { HttpClientModule, HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { NgProgressService } from 'ngx-progressbar';

@Injectable()
export class MyService {
  constructor(private http: HttpClient, private ngProgress: NgProgressService) {}

  getData() {
    this.ngProgress.start();
    return this.http.get('http://example.com/data').pipe(
      finalize(() => this.ngProgress.complete())
    );
  }
}

3. 应用案例和最佳实践

  • 定制样式:你可以通过 CSS 对进度条进行定制,例如改变背景颜色或进度条的颜色。
  • 多实例:在一个页面上可以创建多个进度条,每个都有自己的 ID:
<ng-progress id="instance1"></ng-progress>
<ng-progress id="instance2"></ng-progress>
  • 手动控制:你可以使用组件提供的方法来控制进度条:
<ng-progress #progressBar></ng-progress>

<button (click)="progressBar.start()">开始</button>
<button (click)="progressBar.inc(10)">增加10%</button>
<button (click)="progressBar.complete()">完成</button>

4. 典型生态项目

  • @ngx-progressbar/core: 提供核心进度条组件和服务。
  • @ngx-progressbar/http: 支持跟踪 Http 请求的模块。
  • @ngx-progressbar/router: 监听路由变化并显示加载进度的模块。

以上是 NGX Progressbar 的基本介绍和使用方式,它可以帮助你在开发中为用户提供更好的体验。更多详细信息和高级用法,建议查看官方仓库中的文档和示例。

登录后查看全文
热门项目推荐
相关项目推荐