ngx-nuts-and-bolts

website·Indexed 30 days ago

https://infinum.github.io/ngx-nuts-and-bolts/docs

An NPM library of reusable components and helpers designed to accelerate the development and testing of Angular applications. It includes utilities for form handling (file CVA, form value types), testing (MockStorage, async data/error handling, ExtractPublic), animations, breadcrumbs, loading states, table state management, and environment variable handling.

Tokens
7.2K
Snippets
37
Records
47
Agent score
75%

What's inside ngx-nuts-and-bolts

  1. Overview of EnvironmentVariablesService

    The EnvironmentVariablesService allows Angular applications to handle environment variables without requiring a re-build or re-deployment (only a restart for SSR). This enables the same build/Docker image to be used across multiple environments. It provides methods to read variables and supports custom providers to initialize these values.
  2. Overview of LoadingState features

    LoadingState is a base class that adds loading and error state management to DI providers. Key features include:

    • Debounce Delays: Configurable enter and leave delays prevent the loader from flashing for very short operations.
    • Automatic State Clearing: Starting a new load automatically clears previous errors; setting an error automatically clears the loading state (provided both observables are subscribed to).
    • Initial Load Tracking: Includes an observable to detect if the initial loading process has completed.
    • Retry Mechanism: Provides a loadingTrigger$ observable to restart the RxJS pipeline and an onRetry() handler to trigger it.
    • Direct Access: Use directLoading$ to access the loading state without debounce delays.
  3. Overview of @infinum/ngx-nuts-and-bolts/breadcrumbs

    The @infinum/ngx-nuts-and-bolts/breadcrumbs package provides utilities to set up breadcrumbs by extending route configuration options. It includes a service that exposes an observable array of breadcrumb objects based on the active route and can optionally update the webpage title when breadcrumbs change. The library does not provide visual components, as breadcrumb rendering is intended to be application-specific.
  4. Manage table state using @infinum/ngx-nuts-and-bolts/table-state

    The @infinum/ngx-nuts-and-bolts/table-state library allows developers to move table state (pagination, sorting, and filtering) from application memory into URL query parameters. This enables features like link sharing and page refreshing without losing the current table view. It provides observables to react to query parameter changes and helper functions to update those parameters.
  5. Install ngx-nuts-and-bolts in an Angular project

    Install the @infinum/ngx-nuts-and-bolts library via NPM to access reusable components and helpers designed to accelerate the development and testing of Angular applications. Once installed, you can import specific components or helpers directly into your project as needed.
    npm install @infinum/ngx-nuts-and-bolts
  6. Define breadcrumb data types

    You must define a type T for the BreadcrumbsService to represent the breadcrumbData. This can be a simple string for basic labels or a complex union type to support conditional rendering of different UI elements (e.g., dropdowns or translated keys) in the breadcrumb trail.
    // Simple type
    export type MyAppBreadcrumbData = string;
    
    // Complex type
    export type MyAppBreadcrumbData = UserModel | BlogPostModel | { text: string; isTranslationKey: string };
    
    // Injection
    import { BreadcrumbsService } from '@infinum/ngx-nuts-and-bolts/breadcrumbs';
    const breadcrumbService: BreadcrumbService<MyAppBreadcrumbData> = inject(BreadcrumbsService);
  7. Setup environment variables for SPA applications

    For SPA apps, use provideEnvironmentVariables to initialize the service. The common pattern is to fetch a JSON file (e.g., env.json) from the assets folder at startup. This allows DevOps teams to replace values in the JSON file after the build but before deployment without re-compiling the app.
    // main.ts
    fetch('./assets/env.json')
        .then((response) => response.json())
        .then((env) => {
            platformBrowserDynamic([provideEnvironmentVariables(env)])
                .bootstrapModule(AppModule)
                .catch((err) => console.error(err));
        });
    
    // assets/env.json
    {
        "API_URL": "https://api.example.com"
    }
  8. Mock asynchronous data in service test doubles using asyncData

    When creating test doubles for services that make API calls, avoid using of(data) because it returns the observable synchronously, which does not accurately reflect real-world API behavior. To properly simulate asynchronous behavior and ensure the observable is placed in the event loop queue (via observeOn and asyncScheduler), use the asyncData utility function from @infinum/ngx-nuts-and-bolts/testing-utils to wrap the mock data.
    import { asyncData } from '@infinum/ngx-nuts-and-bolts/testing-utils';
    
    // In your test double service
    public getTestingData(data: TData): Observable<TData> {
        return asyncData(data);
    }
  9. Implement fade and height animations in Angular components

    The @infinum/ngx-nuts-and-bolts/animations library provides two animation factories, fadeAnimation() and heightAnimation(), designed for use within a component's animations array. These animations are triggered in the template using the @fade and @height selectors by default.
    import { fadeAnimation, heightAnimation } from '@infinum/ngx-nuts-and-bolts/animations';
    
    @NgComponent({
        animations: [heightAnimation(), fadeAnimation()],
    })
    export class MyComponent {}
    <button (click)="isOpened = !isOpened">Toggle</button>
    <div *ngIf="isOpened" @fade @height>Lorem ipsum...</div>
  10. Define environment variables using a string enum

    It is recommended to define a string enum for all available environment variables. This enum is used with EnvironmentVariablesService, ENVIRONMENT_VARIABLES_RECORD, and EnvironmentVariablesRecord to ensure type safety and avoid generic string literals.
    export enum EnvironmentVariable {
        Foo = 'NGX_NUTS_AND_BOLTS_EXAMPLE_FOO',
        Bar = 'NGX_NUTS_AND_BOLTS_EXAMPLE_BAR',
    }
  11. Implement a custom environment variables setup using ENVIRONMENT_VARIABLES_RECORD

    For maximum flexibility, you can manually initialize the environment variables record by providing a value for the ENVIRONMENT_VARIABLES_RECORD DI token. The provided object must satisfy the EnvironmentVariablesRecord generic type, which takes an enum of your available variables as its generic parameter.

    Note: If you use this manual approach, do not use the provideEnvironmentVariables or provideUniversalEnvironmentVariables providers, as they perform this action internally.

  12. Manage multiple loading states using helper functions

    If a component must handle multiple independent data sources, it cannot extend LoadingState. Instead, use the privateLoadingState() and publicLoadingState() helper functions to create multiple sets of state observables.
    import { privateLoadingState, publicLoadingState } from '@infinum/ngx-nuts-and-bolts/loading-state';
    
    class MyComponent {
        protected readonly loadingTrigger1$ = new BehaviorSubject<void>(undefined);
        protected readonly _error1$;
        public readonly error1$;
        protected readonly _loading1$;
        public readonly loading1$;
    
        constructor() {
            const _state1 = privateLoadingState();
            const state1 = publicLoadingState(_state1);
            
            this._error1$ = _state1._error$;
            this.error1$ = state1.error$;
            this._loading1$ = _state1._loading$;
            this.loading1$ = state1.loading$;
            
            // Repeat for state2, state3, etc.
        }
    }