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 🙏

© 2024 – Pkg Stats / Ryan Hefner

ngx-error-msg

v0.4.0

Published

A library to map form errors to error messages and display them.

Downloads

411

Readme

NgxErrorMsg

pipeline status Coverage Reliability Rating Security Rating Vulnerabilities

The error message mapping library for Angular.

Live Demo

Features

✅ Dynamic display of error message
✅ Reactive and template driven forms support
✅ I18n libraries support
✅ SSR support
✅ Standalone support

Dependencies

|Angular | |:-------| |15 to 18|

Installation

npm install ngx-error-msg --save

Usage

Standalone directive

The *ngxErrorMsg directive can be used without configuring providers globally. In such a case, the ngxErrorMsgMappings input is required.

NOTE: When using NgModules, import NgxErrorMsgModule.

@Component({
    template: `
       <input
            name="title"
            [(ngModel)]="title"
            required
            minlength="5"
            maxlength="10"
            #titleControl="ngModel" />
        <span *ngxErrorMsg="titleControl.errors; mappings: errorMappings; let message">
            {{ message }}
        </span>
    `,
    imports: [FormsModule, NgxErrorMsgDirective],
    standalone: true,
})
export class AppComponent {
    title = 'example-modules';
    errorMappings: ErrorMessageMappings = {
        required: 'Title is required',
        minlength: error => `Title min length is ${error.requiredLength}`,
        maxlength: error => `Title max length is ${error.requiredLength}`,
    };
}

Global configuration

Step 1: Create a base error mapper.

@Injectable()
export class BaseErrorMsgMapperService extends NgxErrorMsgService {
  protected override readonly errorMsgMappings = {
    required: 'This field is required.',
    minlength: (error) =>
      `This field must be at least ${error.requiredLength} characters long.`,
    maxlength: (error) =>
      `This field must be at most ${error.requiredLength} characters long.`,
  };
}

Step 2: Provide error mapper globally.

bootstrapApplication(AppComponent, {
    providers: [
        provideNgxErrorMsg(BaseErrorMsgMapperService, {errorsLimit: 1}), // The config object is optional.
        // ...
    ],
});

or using Angular module

@NgModule({
  imports: [
    NgxErrorMsgModule.forRoot(BaseErrorMsgMapperService),
  ],
  // ...
})
export class AppModule {}

Step 3: Use the directive.

@Component({
    template: `
        <span *ngxErrorMsg="control.errors; let message">
            {{ message }}
        </span>
    `,
    imports: [NgxErrorMsgDirective],
    standalone: true,
})
export class AppComponent {
    control = new FormControl('', [Validators.required]);
}

Translated messages

NgxErrorMsg library supports mappings to Observable making it possible to use i18n error messages.

@Injectable()
export class BaseErrorMsgMapperService extends NgxErrorMsgService {
  translate = inject(TranslateService); // Or use any other i18n library.

  protected override readonly errorMsgMappings = {
    required: () => this.translate.get('ERRORS.REQUIRED'),
    minlength: (error) => this.translate.get('ERRORS.MIN_LENGTH', {value: error.requiredLength}),
    maxlength: (error) => this.translate.get('ERRORS.MAX_LENGTH', {value: error.requiredLength}),
  };
}

Messages array

The *ngxErrorMsg directive expose messages array which may be used when using a concatenated message is not sufficient e.g. when each message needs to be displayed in a separate line. Message items may contain additional information beyond the message itself, so they are exposed as objects.

<div *ngxErrorMsg="control.errors; messages as messages">
    @for (messageItem of messages; track messageItem.error) {
        {{messageItem.message}}
    }
</div>

Overriding messages and config

The error message mapping priority is based on two factors:

  1. DI tree - mappings of error messages from services closer to the directive are prioritized.
  2. Order in mappings object - error mappings defined first are prioritized.
@Injectable()
export class BaseErrorMsgMapperService extends NgxErrorMsgService {
  protected override readonly errorMsgMappings = {
    email: 'This field is not email.',
    maxlength: `Value too long.`,
  };
}

bootstrapApplication(AppComponent, {
    providers: [
        provideNgxErrorMsg(BaseErrorMsgMapperService, {errorsLimit: -1}), // Don't limit mapped errors.
        // ...
    ],
});
@Injectable()
export class ComponentErrorMsgMapperService extends NgxErrorMsgService {
  protected override readonly errorMsgMappings = {
    maxlength: `The value is too long.`,
  };
}

@Component({
    template: `
        <span *ngxErrorMsg="control.errors; mappings: errorMappings; let message">
            {{ message }} <!-- Title max length is 1. Must be an email. -->
        </span>

        <span *ngxErrorMsg="control.errors; let message">
            {{ message }} <!-- The value is too long. This field is not email. -->
        </span>

        <span *ngxErrorMsg="control.errors; config: {errorsLimit: 1}; let message">
            {{ message }} <!-- The value is too long. -->
        </span>
    `,
    imports: [NgxErrorMsgDirective],
    providers: [provideNgxErrorMsg(ComponentErrorMsgMapperService),],
    standalone: true,
})
export class AppComponent {
    control = new FormControl('long', [Validators.email, Validators.maxLength(1)]);

    errorMappings: ErrorMessageMappings = {
        maxlength: error => `Title max length is ${error.requiredLength}.`,
        email: 'Must be an email.',
    };
}

Using context

Context is designed to pass any additional data that is not part of the error object to error mapping functions.

Context may be passed directly to the directive or be provided using the provideNgxErrorMsgContext function.

@Injectable()
export class Mapper extends NgxErrorMsgService {
  protected override readonly errorMsgMappings = {
    required: (error, ctx) => `${ctx?.fieldName || 'This field'} is required.`,
  };
}
<span *ngxErrorMsg="emailControl.errors; ctx: {fieldName: 'Email'}; let message">
    {{ message }} 
</span>

Simplified mapper creation with createNgxErrorMsgMapper

The createNgxErrorMsgMapper function creates an injectable class from a mappings object or a factory function that returns a mappings object.

provideNgxErrorMsg(
    createNgxErrorMsgMapper({
        required: (error, ctx) => `${ctx?.fieldName || 'This field'} is required.`,
        pattern: 'This field is invalid.'
    })
)

The factory function is executed in an injection context making it possible to inject other services e.g. translation service.

provideNgxErrorMsg(
    createNgxErrorMsgMapper(() => {
        const translate = inject(TranslateService);

        return {
            required: () => translate.get('REQUIRED'),
        }
    })
)

The return value of createNgxErrorMsgMapper is a regular class function that can be assigned to a variable, extended, etc.

const Mapper = createNgxErrorMsgMapper({});

class MyClass extends Mapper {}