DEV Community

Cover image for Implementing Skeleton Loading in Angular 12: A Directive Approach Without NPM Dependencies
Dhruv Kumar
Dhruv Kumar

Posted on

Implementing Skeleton Loading in Angular 12: A Directive Approach Without NPM Dependencies

Introduction
In the dynamic world of front-end development, managing user experience during data loading is crucial. As an Angular developer with a year of experience, I recently faced a unique challenge: integrating skeleton loading into an application without relying on external NPM modules. This task was prompted by the difficulties in resolving dependency issues in an older repository. My solution? A custom Angular directive for skeleton loading.

The Custom Directive Approach
The custom directive I developed in Angular 12 offers a streamlined way to implement skeleton loading. It's designed to render a skeleton component as a placeholder until the data loads and a specific condition is met. This self-contained approach is efficient and aligns with modern development practices in Angular.

Code Explanation
SkeletonDirective

SkeletonDirective
The SkeletonDirective is an Angular directive that dynamically renders skeleton components based on certain inputs. It uses ComponentFactoryResolver to create instances of SkelectonRectComponent.

  1. Inputs: It accepts several inputs like isLoading, size, width, height, and className to customize the skeleton's appearance.
  2. ngOnChanges: This lifecycle hook listens for changes, especially to the isLoading input. When isLoading is true, skeleton rectangles are rendered. Otherwise, the normal content is displayed.

SkelectonRectComponent

SkelectonRectComponent

  1. Styles: The key aspect of this component is its CSS, which uses a shimmer effect to create a skeleton screen. It employs keyframes and linear gradients to achieve this.
  2. Width and Height: The component's width and height can be set via input properties, allowing for flexible layout designs.

Implementation Steps
Implementation Steps
Use the directive in Angular templates where skeleton loading is required.

Conclusion
This custom Angular directive for skeleton loading is a practical solution for enhancing user experience without external dependencies. It demonstrates the power of Angular's directive and component system, offering a flexible and efficient approach to managing UI states during data loading. This method is particularly useful for projects where adding external libraries is not feasible due to compatibility or other constraints.

Top comments (2)

Collapse
 
ahryman40k profile image
Ahryman40k

Do you have the source code associated with this article in your git repos ?

Collapse
 
aixart profile image
Dhruv Kumar

@ahryman40k Currently I don't have any source code , i did this is my company's product . But if you really need the source let me know .