ngxtension Platform

repository·main·Indexed 21 days ago

https://github.com/ngxtension/ngxtension-platform

A modern collection of utilities for Angular providing enhanced capabilities for signals, forms, effects, DOM manipulation, and more. The library features multiple secondary entry points for specialized utilities including active-element, assert-injector, auto-effect, click-outside, computed-previous, and create-signal, among others.

Tokens
87.1K
Snippets
347
Records
442
Agent score
70%

What's inside ngxtension

  1. Overview of ngxtension features

    main

    ngxtension provides a wide range of utilities for modern Angular development, categorized into several domains:

    • Signal Utilities: Advanced computed, derived, and async signals, signal history, lazy signals, etc.
    • DOM & Event Helpers: Click outside, gestures, resize observer, active element, host binding, etc.
    • Forms: Control value accessor helpers, control error, form events, if-validator, etc.
    • RxJS & Effects: Auto effects, explicit effects, create effect, rx-effect, take-latest-from, etc.
    • Injection & DI: Create injectable, create injection token, assert injector, inject-destroy, inject-lazy, inject-network, etc.
    • Array & Object Utilities: Filter array, map array, reduce array, merge-from, not-pattern, etc.
    • Routing: Inject params, inject query params, inject route data/fragment, navigation-end, linked-query-param.
    • Internationalization: Utilities for i18n and formatting.
    • SVG & UI: SVG sprite helpers, repeat pipe, trackBy helpers, etc.
  2. Overview of ngxtension utilities

    main

    ngxtension is a comprehensive collection of over 50 utilities designed for modern Angular development. It is built to leverage the latest Angular features, including Signals, standalone components, and the new control flow.

    Key characteristics include:

    • Modern Angular Focus: Optimized for Signals and the latest change detection systems.
    • Performance & Bundle Size: All utilities are tree-shakable, ensuring you only include what you actually use.
    • Developer Experience: Provides type-safe, intuitive APIs that reduce boilerplate.
    • Broad Coverage: Includes utilities for Signals, Router, Injectors, RxJS, Forms, Pipes, Effects, Lifecycle, Directives, and Components.
  3. What is ngxtension?

    main

    ngxtension is a utilities library for Angular designed to make Angular development easier and more consistent. It aims to provide a 'one-stop shop' for common utilities that developers frequently find themselves re-implementing across different Angular projects.

    Lifecycle Policy: When a feature from ngxtension is eventually implemented in the Angular core, the corresponding ngxtension feature will enter a deprecation process and will be removed in a future major release. This ensures the library focuses on filling current gaps in the Angular ecosystem.

  4. Overview of ngxtension utilities

    main

    ngxtension provides a wide range of utilities for Angular developers, categorized into several functional areas:

    Signal Utilities

    Tools for advanced signal management, including connect, derivedFrom (combineLatest for signals), explicitEffect, createNotifier, signalSlice, toLazySignal, toObservableSignal, mergeFrom, and computedPrevious.

    Router Utilities

    Utilities for interacting with the Angular Router using signals, such as linkedQueryParam (bidirectional binding), injectQueryParams, injectParams, injectRouteData, injectRouteFragment, and injectNavigationEnd.

    Injector Utilities

    Enhanced dependency injection tools like injectLazy, createInjectionToken, injectDestroy (for easy unsubscription), injectNetwork, injectIsIntersecting, injectLocalStorage, injectTextSelection, injectInputs, createInjectable, and autoEffect.

    RxJS Operators

    Custom operators to simplify stream handling, including debug, filterArray, filterNil, mapArray, mapSkipUndefined, poll, whenDocumentVisible, deriveLoading, and takeLatestFrom.

    Forms

    Utilities for Angular Forms, such as ifValidator/ifAsyncValidator for conditional validation, controlValueAccessor for custom controls, controlError for error handling, and formEvents for enhanced event handling.

    Other Utilities

    • Pipes: repeatPipe and call/apply for templates.
    • Effects & Lifecycle: createEffect (standalone NgRx-style), effectOnceIf, and rxEffect.
    • Directives: clickOutside, repeat, resize, and TrackById/TrackByProp.
    • Components: hostBinding (signal-based), svgSprite, and Gesture collection.
    • Miscellaneous: createSingletonProxy, call/apply, intl (i18n), and mergeHttpContext.
  5. Use SignalMap for reactive collections

    main

    SignalMap is a reactive Map implementation designed for Angular's signals system. It provides fine-grained reactivity, meaning changes to a specific key only trigger updates for consumers watching that specific key, rather than re-running everything watching the entire map.

    Import it from ngxtension/collections to manage collections of data where individual item updates should be highly efficient.

    import { SignalMap } from 'ngxtension/collections';
  6. Key features of `linkedQueryParam`

    main

    The linkedQueryParam utility includes several advanced features for managing URL state:

    • Two-way binding: Signal ↔ URL synchronization.
    • Parsing and stringification: Custom logic to convert URL strings to typed values and back.
    • Built-in parsers: Support for common types like numbers and booleans.
    • Default values: Fallback values when the parameter is missing.
    • Coalesced updates: Batches multiple signal updates into a single navigation to optimize performance.
    • Navigation extras: Support for queryParamsHandling, onSameUrlNavigation, replaceUrl, and skipLocationChange.
    • Dynamic keys: Use signals or functions to determine the query parameter key.
    • Source signal integration: Link existing signals (inputs, models, or regular signals) to the URL.
    • Global configuration: Set default behaviors via Angular providers.
  7. Use SignalSet for reactive collections

    main

    SignalSet is a reactive Set implementation designed for Angular's signals system. It provides fine-grained, structure-level reactivity, meaning that updates (like computed values or effect blocks) are only triggered when the membership of the set actually changes. Adding a duplicate value to the set is a no-op and will not trigger reactivity.

    import { SignalSet } from 'ngxtension/collections';
    
    const tags = new SignalSet<string>(['angular', 'typescript']);
    // Adding a duplicate does not trigger reactivity
    tags.add('angular');
  8. When to use ngxtension/gestures vs Angular CDK

    main

    Choosing between ngxtension/gestures and the Angular CDK depends on your requirements for abstraction level and specific features:

    Use ngxtension/gestures when:

    • You need low-level, granular control over gesture data.
    • You want to capture gestures exclusively on specific elements.
    • You are building custom interactions that integrate with animation libraries (e.g., GSAP).

    Use Angular CDK when:

    • You need high-level, ready-to-use features like Drag & Drop (with list reordering, etc.) or Virtual Scrolling.
    • You prefer a more abstracted implementation rather than raw gesture data.
  9. Configure the NgxControlError StateMatcher

    main

    A StateMatcher is a function used to define exactly when a control is considered to be in an "error state". The directive renders its template when the StateMatcher emits true and the control contains at least one of the tracked errors.

    Type Definition:

    export type StateMatcher = (
    	control: AbstractControl,
    	parent?: FormGroupDirective | NgForm,
    ) => Observable<boolean>;

    Default Behavior: The control is in an error state if its status is INVALID and it is either touched or the parent form is submitted.

    Customization Options:

    1. Via Input: Pass the matcher directly to the directive in your template.
    2. Via DI: Provide a global matcher using provideNgxControlError.
    // 1. Define a custom matcher
    export const customErrorStateMatcher: StateMatcher = (control) =>
    	control.statusChanges.pipe(
    		startWith(control.status),
    		map((status) => status === 'INVALID'),
    	);
    
    // 2. Apply via DI (Global)
    provideNgxControlError({ errorStateMatcher: customErrorStateMatcher });
    
    // 3. Apply via Input (Local)
    <strong *ngxControlError="name; track: 'required'; errorStateMatcher: customErrorStateMatcher">
      Name is required.
    </strong>
  10. Compare SignalSet with regular Set

    main

    Use SignalSet instead of a standard Set when your application logic depends on Angular Signals. While a regular Set is more memory-efficient, it cannot trigger updates in computed values or effect blocks when its contents change. SignalSet provides full API compatibility with core Set methods while adding reactivity.

    | Feature             | Regular Set  | SignalSet                 |
    | ------------------- | ------------ | ------------------------- |
    | Reactivity          | ❌ No        | ✅ Yes                    |
    | Works with computed | ❌ No        | ✅ Yes                    |
    | Works with effect   | ❌ No        | ✅ Yes                    |
    | Duplicate handling  | ✅ Yes       | ✅ Yes                    |
    | Insertion order     | ✅ Yes       | ✅ Yes                    |
    | Memory overhead     | Lower        | Slightly higher (signals) |
    | API compatibility   | Full Set API | Core Set methods          |
  11. Understand the concept of signalSlice

    main

    The signalSlice utility is inspired by Redux Toolkit's createSlice. It allows you to declaratively create a "slice" of state that is exposed as a readonly signal.

    Key characteristics:

    • Declarative Updates: All state updates must be declared upfront via sources or actionSources. It is impossible to update the state imperatively.
    • Readonly State: The primary state signal is read-only to ensure data integrity.
    • Automatic Selectors: Top-level properties of the initialState are automatically exposed as individual computed signals on the state object.
    • Action-Driven: State changes are driven by observable streams (sources) or manually triggered actions.
    import { signalSlice } from 'ngxtension/signal-slice';
    
    const state = signalSlice({
      initialState: { checklists: [], loaded: false, error: null },
    });
    
    // Access full state
    console.log(state());
    
    // Access top-level properties as individual signals
    console.log(state.loaded());