npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@ndw-ui-kit/core

v0.5.0

Published

UI components library for Angular

Downloads

1,157

Readme

NDW UI Kit

This repository contains a set of UI components for an Angular application. It supports Angular 20.

Installation

npm install @angular/cdk @ndw-ui-kit/core
yarn add @angular/cdk @ndw-ui-kit/core
pnpm add @angular/cdk @ndw-ui-kit/core

Usage

Including relevant assets in your project configuration

Components in the NDW UI kit rely on SCSS files shipped as part of the npm package. You need to add these files in relevant parts of your project's angular.json to ensure the components are styled correctly. The snippet below shows an example — repeat the same assets and styles entries in each build configuration you use (e.g. development, production):

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "projects": {
    "<YOUR_PROJECT_NAME>": {
      // ...
      "architect": {
        "build": {
          "options": {
            "assets": [
              // core icons sprite
              {
                "glob": "ndw-ui-kit.sprite.svg",
                "input": "node_modules/@ndw-ui-kit/core/assets",
                "output": "/assets/"
              },

              // pictogram icons sprite
              {
                "glob": "ndw-ui-kit.pictogram.sprite.svg",
                "input": "node_modules/@ndw-ui-kit/core/assets",
                "output": "/assets/"
              },
              // ... other assets
            ],
            "styles": [
              "./node_modules/@ndw-ui-kit/core/styles/themes.scss",
              // ... other styles
            ]
          }
          // Repeat the same assets/styles in each configuration block
        }
      }
    }
  }
}

The package exports @ndw-ui-kit/core/styles/* and @ndw-ui-kit/core/assets/*, so other bundlers (e.g. Vite) can import them by package name without extra includePaths or loadPaths:

@use '@ndw-ui-kit/core/styles/themes';
import spriteUrl from '@ndw-ui-kit/core/assets/ndw-ui-kit.sprite.svg?url';

Theming

The NDW UI kit has two built-in themes: light and dark. To switch between them, add or remove the ndw-theme-dark class on the root element:


<body><!-- light theme is the default --></body>
<body class="ndw-theme-dark"><!-- dark theme --></body>

Fonts

The NDW UI kit uses Roboto as the default font family. By default, @ndw-ui-kit/core/styles/themes.scss does not emit Roboto @font-face declarations. This avoids duplicating font assets when your application already provides Roboto.

If you want the UI kit to emit Roboto @font-face rules, create a small wrapper stylesheet in your app and configure the theme module with Sass @use ... with (...):

// src/styles/ndw-ui-kit-theme.scss
@use '@ndw-ui-kit/core/styles/themes' with (
  $ndwu-emit-font-faces: true,
  $ndwu-roboto-font-base-path: '/assets/fonts/roboto'
);

Then include that wrapper stylesheet in your angular.json styles instead of pointing directly to node_modules/@ndw-ui-kit/core/styles/themes.scss.

When enabling library-managed fonts, make sure the Roboto .woff2 files are also copied to the path referenced by $ndwu-roboto-font-base-path.

UI kit components set their own font family and do not inherit the page font. To use a different font for all components, set --ndwu-font-family on :root:

:root {
  --ndwu-font-family: Inter, sans-serif;
}

Set it on :root (or body), not on an inner container: dropdowns, tooltips, popovers and modals render in an overlay attached to body and would not see a container-scoped value. Use a real font stack — inherit does not restore the page font.

Accessibility

The library ships an aria module (@ndw-ui-kit/core/aria) that provides ARIA-compliant listbox and combobox primitives used internally by select/multiselect components. These components produce appropriate role, aria-*, and keyboard-navigation attributes out of the box — no additional configuration is required.

Dialog and drawer custom slots

Dialogs and drawers support structural slot directives for replacing the container's default header and footer regions:

  • *ndwuModalHeader
  • *ndwuModalFooter
  • ndwuModalActions

Structural vs attribute usage

Use the structural form when you want to render content in the real outer modal container:


<section *ndwuModalHeader>
  <h3>Custom header</h3>
</section>

<div ndwuModalBody>
  Body content
</div>

<div
  *ndwuModalFooter
  ndwuModalActions
>
  <button ndwuButton label="Cancel"></button>
</div>

Keep using the attribute form when you only need the built-in body/header/footer styles inside already-rendered modal content:


<div ndwuModalFooter>
  Styled footer content inside the modal body
</div>

Important difference:

  • *ndwuModalHeader / *ndwuModalFooter — replace the container header/footer.
  • ndwuModalActions — marks the real element inside a custom footer as its action row. It adds global action-row styles because custom footer content is projected into the outer dialog/drawer and consumer component-scoped selectors cannot style its buttons. On mobile, buttons stretch with a 16px gap. Default footers apply this automatically.
  • ndwuModalHeader / ndwuModalFooter on a normal element — styling helper only
  • ndwuModalBody — styling helper for the body area

Use ndwuModalActions with *ndwuModalFooter on a real element such as div; ng-container has no host element for the action-row class.

When a custom slot is present:

  • the default title/description header is not rendered for that modal instance
  • config.buttons are not rendered when a custom footer slot is present
  • the feature works for both dialogs and drawers

Component content example

import {
  NDWU_MODAL_REF,
  NdwuButtonComponent,
  NdwuModalActionsDirective,
  NdwuModalFooterDirective,
  NdwuModalHeaderDirective,
  NdwuModalRef,
} from '@ndw-ui-kit/core';

@Component({
  // ...
  imports: [
    NdwuButtonComponent,
    NdwuModalActionsDirective,
    NdwuModalHeaderDirective,
    NdwuModalFooterDirective,
  ],
})
export class ProfileDialogComponent {
  constructor(
    @Inject(NDWU_MODAL_REF) protected readonly modalRef: NdwuModalRef<boolean>,
  ) {
  }
}

<section *ndwuModalHeader>
  <h3 tabindex="0">Profile settings</h3>

  <button
    ndwuButton
    variant="secondary"
    label="Close"
    (click)="modalRef.close(false)"
  >
  </button>
</section>

<div>
  Dialog or drawer body content.
</div>

<div
  *ndwuModalFooter
  ndwuModalActions
>
  <button
    ndwuButton
    variant="secondary"
    label="Cancel"
    (click)="modalRef.close(false)"
  >
  </button>

  <button
    ndwuButton
    variant="primary"
    label="Save"
    (click)="modalRef.close(true)"
  >
  </button>
</div>
this.modalService.openDialog(
  ProfileDialogComponent,
  {
    ariaLabel: 'Profile settings',
    hasCloseButton: false,
    width: '560px',
  },
);

The same component can also be opened with openDrawer(...).

ng-template content example


<ng-template #templateDialog let-modalRef="modalRef">
  <section *ndwuModalHeader>
    <h3>Template header</h3>
  </section>

  <div ndwuModalBody>
    Content rendered from an `ng-template`.
  </div>

  <div
    *ndwuModalFooter
    ndwuModalActions
  >
    <button
      ndwuButton
      variant="primary"
      label="Close"
      (click)="modalRef.close()"
    >
    </button>
  </div>
</ng-template>
this.modalService.openTemplate(
  this.templateDialog(),
  {
    type: 'dialog',
    viewContainerRef: this.viewContainerRef,
    config: {
      ariaLabel: 'Template dialog with custom slots',
      hasCloseButton: false,
      width: '560px',
    },
  },
);

Accessibility guidance

If a custom header replaces the default title block, make sure the dialog/drawer still has an accessible name:

  • prefer explicit ariaLabel, or
  • provide ariaLabelledby that points to an element rendered inside your custom header

If title is still provided and no explicit accessible-name override is set, the library uses that title as a fallback accessible name for modals with a custom header slot.

Icons

By default, <ndwu-icon> uses only the core sprite (ndw-ui-kit.sprite.svg).

Additional icons (full catalog)

If you need access to the full icon catalog (~330 extra icons), include the extra sprite asset in angular.json (using ndw-ui-kit.extra.sprite.svg) and register the provider:

import {provideNdwuAllIcons} from '@ndw-ui-kit/core';

export const appConfig: ApplicationConfig = {
  providers: [
    provideNdwuAllIcons(),
  ],
};

Custom sprite (subset of extra icons)

If you only need a small subset of extra icons, generate a custom sprite instead of shipping the full extra sprite. This reduces your production bundle size while preserving runtime checks inside <ndwu-icon>.

1. Create an icon config file
{
  "icons": [
    "wifi_signal_1_L",
    "wifi_signal_2_L",
    "usb_L"
  ]
}

Icon names are string values of NDWU_EXTRA_ICON_NAME exported from @ndw-ui-kit/core. The CLI validates every name and exits an error for any unknown name.

2. Generate the sprite
npx ndw-ui-kit-build-sprite --config src/my-icons.json --out src/assets/my-custom.sprite.svg
3. Serve the generated sprite as a static asset
{
  "assets": [
    {
      "glob": "my-custom.sprite.svg",
      "input": "src/assets",
      "output": "/assets/"
    }
  ]
}
4. Register the custom sprite in your app
import {provideNdwuCustomIcons} from '@ndw-ui-kit/core';

export const appConfig: ApplicationConfig = {
  providers: [
    provideNdwuCustomIcons({
      path: 'assets/my-custom.sprite.svg',
      // you can also load the list of icons directly from the JSON config file here
      // if you add `resolveJsonModule: true` to your app's tsconfig
      iconNames: ['wifi_signal_1_L', 'wifi_signal_2_L', 'usb_L'],
    }),
  ],
};

provideNdwuCustomIcons always includes the core sprite automatically, so there is no need to configure it separately. The <ndwu-icon> component will warn at runtime if an icon name is used that was not included in the configured set.

Pictograms

Pictograms are a separate set of ~10 two-colored icons used inside certain @ndw-ui-kit/core components. Those icons are merged into an additional SVG sprite file (ndw-ui-kit.pictogram.sprite.svg) that should be included in your app's assets if you use any component that relies on pictograms (e.g., NdwuEmptyStateComponent from @ndw-ui-kit/core/widgets).

Router loader

<ndwu-router-loader> is an animated two-colored loader. The SVG is inlined, so it needs no sprite asset.

<ndwu-router-loader />                            <!-- XL, 100×100 (default) -->
<ndwu-router-loader size="L" />                   <!-- L, 64×64 -->
<ndwu-router-loader firstColor="#66AC20" secondColor="#D4ECBD" />
<ndwu-router-loader [duration]="3000" />         <!-- one cycle in ms, 1500 by default -->
  • By default, colors come from the --ndwu-router-loader-first-color / --ndwu-router-loader-second-color tokens and follow the active theme. firstColor / secondColor override them for a single instance.
  • duration scales the whole animation cycle proportionally. Non-positive or non-numeric values fall back to 1500.
  • The accessible name defaults to Loading and goes through the localize pipe. Use ariaLabel to change it.
  • With prefers-reduced-motion: reduce, the animation is turned off.

Tag

<button ndwu-tag> is an interactive tag. For a static label, use <ndwu-badge>.

<button ndwu-tag selectable [(selected)]="isActive" label="Online"></button>
<button ndwu-tag removable label="Wi-Fi" (removed)="removeFilter('wifi')"></button>
  • A removable tag announces Remove after its label. The text goes through the localize pipe; use removeLabel to change it. ariaLabel replaces the whole accessible name, so include the remove action in it yourself.
  • Delete and Backspace on a focused removable tag emit removed and call preventDefault(). The event still bubbles, so document-level keyboard shortcuts must skip events with defaultPrevented.

Localization

Without a translation provider, components show texts and translation keys as-is (NdwuNoopTranslationService is used by default). To localize them, use one of the following options:

  • Ngx-Translate Integration (depends on @ngx-translate/core):

    import {provideNdwuNgxTranslate} from '@ndw-ui-kit/core/l10n/ngx-translate';
    
    providers: [provideNdwuNgxTranslate()]

    Since this version the ngx-translate integration lives in a separate entry point @ndw-ui-kit/core/l10n/ngx-translate (previously exported from @ndw-ui-kit/core/l10n), so the package no longer requires @ngx-translate/core unless you import it.

  • Custom translation service: extend NdwuTranslationService and provide it:

    import {NdwuTranslationService} from '@ndw-ui-kit/core/l10n';
    
    providers: [{provide: NdwuTranslationService, useClass: MyTranslationService}]

provideNdwuNoopTranslation() is optional. Use it to replace another translation service in a child injector.

HTML in text inputs

These inputs are translated with the localizeHtml pipe. A translated string is rendered as trusted HTML, so inline styles such as style="position: relative; top: 2px" are kept:

  • ndwu-notification: message.
  • ndwu-empty-state: header, description.
  • ndwuTooltip.
<ndwu-notification message="setup.led-hint" />

A string without a translation is sanitized by Angular, so inline styles are removed from it. To render other HTML as-is, pass a SafeHtml value; it is not translated.

Component size

Components support size variants: S, L, XL, XXL (not all components support every value). Specify size on individual components:


<ndwu-button [size]="NDWU_SIZE.L">Submit</ndwu-button>

Use ndwu-form-container to set size for all child components at once:


<ndwu-form-container [size]="NDWU_SIZE.XL">
  <ndwu-form-field>
    <ndwu-label>Email</ndwu-label>
    <input ndwuInput formControlName="email"/>
  </ndwu-form-field>
  <ndwu-button>Submit</ndwu-button>
</ndwu-form-container>

Size resolution priority:

  1. Explicit [size] on the component itself
  2. Inherited from the nearest parent container
  3. Default (NDWU_SIZE.XL)

Component tokens

You can customize component appearance by overriding CSS custom properties emitted by the UI kit theme (--ndwu-...).

Use token overrides at the scope that matches your needs.

Global override (all instances)

:root {
  --ndwu-card-border-color: #8b5cf6;
  --ndwu-card-bg: #f8f5ff;
}

Theme-scoped override

.ndwu-theme-dark {
  --ndwu-card-border-color: #22d3ee;
  --ndwu-card-bg: #062b33;
}

Per-container override (single section/page)

To customize a specific component instance, create a custom class and apply it to a wrapping container:

<div class="custom-card-theme">
  <ndwu-card>
    Custom card content
  </ndwu-card>
</div>
.custom-card-theme {
  --ndwu-card-border-color: #7c3aed;
  --ndwu-card-bg: #f5f3ff;
  --ndwu-card-color: #1f2937;
}

Tip: inspect component styles (or playground examples) to find the exact token names used by a specific component.

Widgets

Composite components that are built on top of basic ones have a separate entry point (@ndw-ui-kit/core/widgets), so apps that don't use them don't pull them in together with basic components.

| Component | Description | |------------------------|-------------------------------| | ndwu-empty-state | Empty state with a pictogram | | ndwu-file-upload | File dropzone with file list | | ndwu-schedule-editor | Weekly schedule editor canvas |

import {NdwuEmptyStateComponent} from '@ndw-ui-kit/core/widgets';

Their form control wrappers (ndwu-file-upload-field, ndwu-schedule-editor-field) stay in @ndw-ui-kit/core/form-field.

Schedule actions

Conversion between the ndwu-schedule-editor value (NdwuScheduleValue) and a list of start/stop actions ({action, hour, min, dow}) has a separate entry point (@ndw-ui-kit/core/schedule-actions), so apps that don't need it don't pull it in.

import {ndwuActionsToScheduleValue, ndwuScheduleValueToActions} from '@ndw-ui-kit/core/schedule-actions';

const actions = ndwuScheduleValueToActions(value, weekDays);
const restored = ndwuActionsToScheduleValue(actions, weekDays);

Form field components (CVA)

The ndw-ui-kit provides a number o CVA components for common form controls (checkbox, input, select, etc.). These implement Angular's ControlValueAccessor and have a separate entry point (@ndw-ui-kit/core/form-field).

| Component | Description | |------------------------------|------------------------| | ndwu-autocomplete-field | Text input with hints | | ndwu-checkbox-field | Checkbox (two-state) | | ndwu-input-field | Text/password input | | ndwu-multi-select-field | Multi-option select | | ndwu-radio-field | Radio button list | | ndwu-schedule-editor-field | Weekly schedule editor | | ndwu-select-field | Single-option select | | ndwu-textarea-field | Multi-line text input | | ndwu-toggle-field | Toggle switch |

Browser autofill

ndwuInput tracks browser autofill (:autofill) to keep the floating label raised over an autofilled value.

Known limitation: Chrome/Edge autofill on page load only displays the value. Until the first user interaction with the page, both el.value and the Angular control value stay empty. This can't be fixed on the library side.

Custom option lists

Select, multi-select, and radio components accept either NdwuOption[] directly or domain arrays together with an optionAdapter. Autocomplete has no adapter: it accepts only NdwuAutocompleteOption[], and the project-wide default adapter doesn't apply to it.

Autocomplete options can set variant: 'danger' directly. Both autocomplete components also accept maxVisibleOptions; it limits visible rows on desktop and is ignored in the mobile sheet. Use ndwuOptionTemplate to render custom content and highlight the current trimmed query:

<ndwu-autocomplete-field [options]="options" [maxVisibleOptions]="4">
  <ng-template
    [ndwuOptionTemplate]="options"
    let-raw="raw"
    let-label="label"
    let-query="query"
  >
    <ndwu-icon
      [name]="raw?.icon"
      aria-hidden="true"
    />
    <ndwu-option-label>{{ label }}</ndwu-option-label>
    <mark>{{ query }}</mark>
  </ng-template>
</ndwu-autocomplete-field>

Autocomplete template context provides the normalized option through $implicit, the original raw item matched by value, displayed label, disabled, and query. selected is always false; other option templates leave query undefined. Import NdwuOptionTemplateDirective and NdwuOptionLabelComponent from @ndw-ui-kit/core and bind the original options array to type raw; this binding is required. Use <ndwu-option-label> for option text so it truncates with "…" on desktop and clamps to two lines in the mobile sheet.

import {NdwuOptionAdapter} from '@ndw-ui-kit/core';

interface Country {
  code: string;
  name: string;
  isDisabled?: boolean;
  isDanger?: boolean;
}

const countries: Country[] = [
  {code: 'de', name: 'Germany'},
  {code: 'ch', name: 'Switzerland'},
];

const countryAdapter: NdwuOptionAdapter<Country> = {
  value: 'code',          // key selector: resolves Country.code
  label: 'name',          // key selector: resolves Country.name
  disabled: 'isDisabled', // optional
};
Danger options

Set variant: 'danger' on an NdwuOption to show destructive options in red. The default adapter reads variant; domain arrays can map it with a key or function selector. Danger options use the standard selected, active, and disabled backgrounds. An unselected, enabled danger option uses a pale red hover fill.

const countryAdapter: NdwuOptionAdapter<Country> = {
  value: 'code',
  label: 'name',
  variant: (country) => country.isDanger ? 'danger' : undefined,
};
<ndwu-select-field
  [options]="countries"
  [optionAdapter]="countryAdapter"
  formControlName="country"
/>
Maximum visible options

Use maxVisibleOptions to change how many option rows appear before the list scrolls. It counts group headers too and is ignored in the mobile sheet. When omitted or null, the list keeps its size default (L: 9, XL: 8, XXL: 7).

<ndwu-select-field
  [options]="countries"
  [maxVisibleOptions]="4"
  formControlName="country"
/>
Custom option template

Use ndwuOptionTemplate to replace option content with an icon, status marker, or other domain-specific UI. Import NdwuOptionTemplateDirective and NdwuOptionLabelComponent from @ndw-ui-kit/core. Binding the original options array to the directive is required so Angular can type raw:

<ndwu-select-field [options]="environments" formControlName="environment">
  <ng-template
    [ndwuOptionTemplate]="environments"
    let-raw="raw"
    let-label="label"
    let-selected="selected"
    let-disabled="disabled"
  >
    <ndwu-icon
      [name]="raw?.icon"
      aria-hidden="true"
    />
    <ndwu-option-label>{{ label }}</ndwu-option-label>
    <span
      class="status-dot"
      [style.backgroundColor]="raw?.statusColor"
      aria-hidden="true"
    ></span>
  </ng-template>
</ndwu-select-field>

The template context exposes $implicit (normalized option), raw (original item matched by value), localized label, selected, and disabled. In multi-select, the template replaces only the label; the checkbox remains. The consumer controls truncation for long custom content.

Selectors can also be functions when you need computed values:

const countryAdapter: NdwuOptionAdapter<Country> = {
  value: (c) => c.code,
  label: (c) => `${c.name} (${c.code})`,
};
Project-wide default adapter

If your project mostly uses a single option shape across these components, you can provide a default adapter via DI:

import {NDWU_OPTION_CONFIG} from '@ndw-ui-kit/core';

providers: [
  {
    provide: NDWU_OPTION_CONFIG,
    useValue: {optionAdapter: countryAdapter}, // default adapter for all option-based components
  },
]
Multi-select custom trigger display

Use ndwuMultiSelectDisplay to render a custom trigger template for multiselect. The template context provides both the original selected options (selectedOptions) and the internal normalized option list (normalizedOptions):

<ndwu-multi-select-field [options]="countries" [optionAdapter]="countryAdapter">
  <ng-template
    ndwuMultiSelectDisplay
    let-normalizedOptions="normalizedOptions"
    let-selectedOptions="selectedOptions"
    let-selectedValues="selectedValues"
    let-empty="empty"
  >
    @if (empty) {
      <span>No countries selected</span>
    } @else {
      <span>{{ selectedOptions.length }} selected</span>
    }
  </ng-template>
</ndwu-multi-select-field>

Validation

The NDW UI Kit shows validation errors for CVA components (currently ndwu-input-field). Errors are only displayed after the control is touched.

ndwuInput without Angular forms

Without Angular forms the directive tracks interaction itself. Native :invalid state shows only after input or blur; form.reset() clears it. The result is written to aria-invalid.

To set the state explicitly, use aria-invalid="true|false" or [aria-invalid]="expr". It overrides computed state. Do not use [attr.aria-invalid]: it writes the attribute directly and conflicts with the directive. With Angular forms the control state is used and aria-invalid input is ignored.

Built-in validators

Angular's Validators return errors without a message key, so the fields show no text for them. Use NdwuValidators instead. They validate like Angular's and add a translation key to each error:

import {NdwuValidators, ndwuWrapValidator} from '@ndw-ui-kit/core/form-field';

name: new FormControl('', [
  NdwuValidators.required(),                                 // 'ndwu.validation.required'
  NdwuValidators.minLength(3),                               // 'ndwu.validation.min-length'
  NdwuValidators.maxLength(20, 'signup.name-too-long'),      // custom key
  ndwuWrapValidator(noSpacesValidator, 'signup.no-spaces'),  // any other validator
]),

Add the ndwu.validation.* keys to your translations. The error fields become placeholders, e.g. "Enter at least {{requiredLength}} characters". The keys are exported as NDWU_VALIDATION_ERROR_LABEL. For the full key and placeholder list and the design, see ADR 009.

Use the ndwuRequired input to show the required mark. Don't put Angular's required, email, minlength, maxlength or pattern attributes on ndwu fields: their validator directives replace the NdwuValidators errors.

ndwuRequired on ndwu-checkbox-field and ndwu-radio-field also sets required on the native inputs. It only marks the field as required and doesn't validate anything: add a validator to the control. If your prefer builtin Angular validators, for a checkbox use Validators.requiredTrue, because Validators.required treats false as a valid value.

How it works

A validator returns NdwuValidatorResult (either null for success or NdwuErrorResult):

import {AbstractControl} from '@angular/forms';
import {NdwuErrorResult, NdwuValidatorResult} from '@ndw-ui-kit/core/form-field';

// Helper functions (define these in your app):
function ERROR(props: {key: string; value?: any}): NdwuErrorResult {
  return {[props.key]: {errorLabel: props.key, ...props}};
}

function SUCCESS(): null {
  return null;
}

const requiredValidator = (control: AbstractControl): NdwuValidatorResult => {
  const value = control.value;
  const isInvalid = value === undefined || value === '' || value === null;
  return isInvalid ? ERROR({key: 'This field is required', value}) : SUCCESS();
};

The built-in processor converts NdwuValidatorError (an object with errorLabel) into NdwuValidationData:

export interface NdwuValidationData {
  errorMessage: string;
  validationData?: Record<string, any>;
}

Custom validation processor

For built-in Angular validators, prefer NdwuValidators (see above). Override the built-in processor via the NDWU_VALIDATION_PROCESSOR token only if your validators return errors in a different shape that you can't wrap:

import {AbstractControl} from '@angular/forms';
import {NDWU_VALIDATION_PROCESSOR, NdwuValidationData} from '@ndw-ui-kit/core/form-field';

const customProcessor = (control: AbstractControl): NdwuValidationData | null => {
  const errors = control?.errors;
  if (!errors) return null;

  if (errors['required']) {
    return {errorMessage: 'validation.required'};
  }

  if (errors['minlength']) {
    return {
      errorMessage: 'validation.minlength',
      validationData: {
        requiredLength: errors['minlength'].requiredLength,
        actualLength: errors['minlength'].actualLength,
      },
    };
  }

  return null;
};

export const appConfig: ApplicationConfig = {
  providers: [
    {provide: NDWU_VALIDATION_PROCESSOR, useValue: customProcessor},
  ],
};