咨询适配Angular 12的ngx-skeleton-loader合适版本
适配Angular 12的ngx-skeleton-loader版本及实现步骤
适配版本说明
Angular 12 对应的 ngx-skeleton-loader 兼容版本为 v8.x.x 系列(如 8.0.0 或更高的8.x版本)。后续版本(v9及以上)依赖Angular 13+,直接安装最新版会触发兼容性错误。
安装适配版本的命令:
npm install ngx-skeleton-loader@^8.0.0 # 或使用yarn yarn add ngx-skeleton-loader@^8.0.0
功能实现步骤
1. 引入模块
在需要使用骨架屏的Angular模块(如AppModule或业务模块)中导入NgxSkeletonLoaderModule:
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { NgxSkeletonLoaderModule } from 'ngx-skeleton-loader'; import { AppComponent } from './app.component'; @NgModule({ declarations: [AppComponent], imports: [BrowserModule, NgxSkeletonLoaderModule], bootstrap: [AppComponent] }) export class AppModule { }
2. 模板中使用骨架屏
通过*ngIf控制加载状态,数据未就绪时显示骨架屏,加载完成后切换为实际内容:
<!-- 骨架屏状态 --> <ng-container *ngIf="!isDataLoaded; else contentView"> <!-- 模拟3条列表项的骨架屏 --> <div class="skeleton-item" *ngFor="let _ of [1,2,3]"> <ngx-skeleton-loader [theme]="{ height: '56px', width: '100%', borderRadius: '6px', marginBottom: '16px' }" ></ngx-skeleton-loader> </div> </ng-container> <!-- 实际内容视图 --> <ng-template #contentView> <div class="data-item" *ngFor="let item of dataList"> <h3>{{ item.title }}</h3> <p>{{ item.description }}</p> </div> </ng-template>
3. 组件类控制加载逻辑
模拟异步数据请求,切换加载状态:
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { isDataLoaded = false; dataList: Array<{title: string, description: string}> = []; ngOnInit(): void { // 模拟API请求延迟 setTimeout(() => { this.dataList = [ { title: '文章标题1', description: '这是文章的描述内容' }, { title: '文章标题2', description: '这是文章的描述内容' }, { title: '文章标题3', description: '这是文章的描述内容' } ]; this.isDataLoaded = true; }, 2000); } }
4. 自定义样式(可选)
通过CSS变量调整骨架屏的外观和动画:
/* 全局或组件内样式 */ ngx-skeleton-loader { --ngx-skeleton-loader-background: #f5f5f5; --ngx-skeleton-loader-loader-background: #e0e0e0; /* 调整动画速度 */ --ngx-skeleton-loader-animation-duration: 1.5s; }
内容的提问来源于stack exchange,提问作者Ajmal Rahman
相关产品推荐
相关产品推荐

