Skip to content

Docs: Utils

ng-druid edited this page Aug 8, 2025 · 1 revision

Documentation for Angular Utils Library

Table of Contents

  1. Introduction
  2. Installation
  3. Overview
  4. Core Module
  5. Key Components
  6. Directives
  7. Pipes
  8. Services
  9. Tokens
  10. Data Services
  11. Usage Examples
  12. Testing

1. Introduction

The Angular Utils Library provides utility components, directives, pipes, services, and tokens to simplify application development. This shared library contains reusable elements that can be used across multiple projects, offering functionality like dynamic content rendering, numeral formatting, custom structural directives, data services, and module loaders.


2. Installation

Install the library and its dependencies using npm:

npm install @your-org/utils

3. Overview

The UtilsModule is the main module exported by this library. It aggregates all utilities into a single module that can be imported into any Angular application.

Features:

  • Dynamic Content Rendering via DynamicContentViewerComponent.
  • Custom Structural Directives like ForDirective.
  • Pipes for numeral formatting and handling empty values (NotAvailablePipe, NumeralPipe).
  • Runtime Module Loading via ModuleLoaderService.
  • Style Loading for dynamically applying themes via StyleLoaderService.
  • Noop Data Service for mock data handling.
  • Async API Call Helpers for handling promises as observables.

4. Core Module

UtilsModule

The UtilsModule is the primary entry point for the library. It includes declarations and exports for all components, directives, pipes, and other utilities.

@NgModule({
  imports: [CommonModule],
  declarations: [
    NumeralPipe,
    NotAvailablePipe,
    DynamicContentViewer,
    ForDirective,
  ],
  exports: [
    NumeralPipe,
    NotAvailablePipe,
    DynamicContentViewer,
    ForDirective,
  ],
})
export class UtilsModule {}

To use the module, import it into your application:

import { UtilsModule } from '@your-org/utils';

@NgModule({
  imports: [UtilsModule],
})
export class AppModule {}

5. Key Components

5.1 Dynamic Content Viewer Component (DynamicContentViewer)

The DynamicContentViewer is designed to render dynamic content at runtime. It parses HTML content and dynamically instantiates Angular components embedded within.

Key Features:

  • Dynamic Component Rendering: Automatically matches selectors for embedded components.
  • Event Output: Emits an event when the content is fully rendered.

Inputs:

  • content: Raw HTML content with embedded Angular components.
  • data: Data passed to the component.

Outputs:

  • docRendered: Emits when the content has been successfully rendered.

Example Usage:

<classifieds-ui-dynamic-content-viewer
  [content]="htmlContent"
  [data]="contentData"
  (docRendered)="onContentRendered()"
></classifieds-ui-dynamic-content-viewer>

6. Directives

6.1 For Directive (ForDirective)

The ForDirective is a custom structural directive that creates elements in a loop. It also provides convenient context variables (even, odd, first, and last) for use within templates.

Example Usage:

<div *for="5">
  Index: {{ index }}, Even: {{ even }}, First: {{ first }}, Last: {{ last }}
</div>

This will render the block five times, with the context variables dynamically updated for each instance.


7. Pipes

7.1 Numeral Pipe (NumeralPipe)

Transforms numbers using formatting rules.

Features:

  • Converts string-based numbers into Number objects.
  • Supports numeral transformations (basic number formatting).

Example Usage:

<span>{{ value | numeral: '0,0.00' }}</span>

7.2 Not Available Pipe (NotAvailablePipe)

Provides a default fallback for empty or invalid values.

Example Usage:

<span>{{ value | na: 'Default Value' }}</span>

If value is null or empty, 'Default Value' is displayed.


8. Services

8.1 Module Loader Service (ModuleLoaderService)

Dynamically loads Angular modules at runtime. Useful for lazy loading modules or features dynamically.

Example:

constructor(private moduleLoader: ModuleLoaderService) {}

loadModule() {
  this.moduleLoader.loadModule(() => import('./lazy/lazy.module'));
}

8.2 Style Loader Service (StyleLoaderService)

Dynamically loads and applies stylesheet themes by updating the <link> element.

Example:

constructor(private styleLoader: StyleLoaderService) {}

applyTheme(theme: string) {
  this.styleLoader.loadStyle(`/assets/themes/${theme}.css`);
}

8.3 Async API Call Helper Service (AsyncApiCallHelperService)

Converts promises into observables, making asynchronous tasks more manageable and cancelable.

Example Usage:

constructor(private asyncHelper: AsyncApiCallHelperService) {}

processTask() {
  this.asyncHelper.doTask(fetch('/api/data')).subscribe({
    next: (result) => console.log(result),
    error: (err) => console.error(err),
  });
}

9. Tokens

The library defines custom InjectionTokens for dependency injection configurations.

  • EMBEDDABLE_COMPONENT: Injects dynamic embeddable components into DynamicContentViewerComponent.
  • SITE_NAME: String token for the site name.
  • HOST_NAME: String token for the host name.
  • PROTOCOL: String token for the request protocol.

Example Usage:

providers: [
  { provide: SITE_NAME, useValue: 'MySite' },
  { provide: HOST_NAME, useValue: 'example.com' },
  { provide: PROTOCOL, useValue: 'https' },
]

10. Data Services

NoopDataService

Provides a mock implementation of EntityCollectionDataService. This is useful for testing or temporary mock data setup.

Key Methods:

  • add(entity: T): Adds an entity.
  • delete(id: number | string): Deletes an entity by its ID.
  • getAll(): Retrieves all entities.
  • getById(id: any): Retrieves an entity by its ID.
  • Other CRUD operations (getWithQuery, update, upsert).

Example Usage:

const service = new NoopDataService<any>('mock');
service.add({ id: 1, name: 'Test' }).subscribe((data) => console.log(data));

11. Usage Examples

Example: Dynamic Component Rendering

<classifieds-ui-dynamic-content-viewer
  [content]="htmlContent"
  [data]="componentData"
></classifieds-ui-dynamic-content-viewer>
htmlContent = `<custom-element></custom-element>`;
componentData = { key: 'value' };

Example: Infinite Loop Display

<div *for="10">Iteration {{ index }}</div>

Example: Handling Async API Tasks

constructor(private asyncHelper: AsyncApiCallHelperService) {}

processApiCall() {
  this.asyncHelper.doTask(fetch('/api/items')).subscribe({
    next: (data) => console.log(data),
    error: (err) => console.error(err),
  });
}

12. Testing

The library components, directives, pipes, and services can be tested using standard Angular testing utilities and Karma.

Unit Test for Pipes:

import { NumeralPipe } from './numeral.pipe';

describe('NumeralPipe', () => {
  it('should create an instance', () => {
    const pipe = new NumeralPipe();
    expect(pipe).toBeTruthy();
  });
});

Conclusion

The Angular Utils Library provides reusable utility components, directives, pipes, and services to simplify application development. Incorporate this library wherever you need dynamic rendering, numeral handling, or runtime module and style management in your Angular applications.

For contributions or feature requests, feel free to contact the development team!

Clone this wiki locally