Ninja-Squad/ngx-valdemort

How to set default error messages in module constructor?

Closed this issue · 1 comments

Is there a way to declare default error messages in TS code in module constructor, similar where we can set ValdemortConfig parameters?

I'm investigating a way we could implement a shared module (ie. GlobalValidationErrorsModule) that will define global error messages, so we could import it in all of our multiple angular projects/modules that are using form validation. Ideally, any of our multiple angular projects/modules that imported the shared module GlobalValidationErrorsModule should automatically use global errors without having to declare them in their html templates. The basic usage requires we put default errors inside html template (in each page with form or globally inside app.component.html). But is there a way we can "inject" default error messages in a shared module's constructor, so other projects that import this shared module won't have declare anything?

I tried the following code in our shared module constructor:

validation-errors.module.ts
@NgModule(...)
export class ValidationErrorsModule { 
  constructor(private environmentInjector: EnvironmentInjector, private appRef: ApplicationRef) {
    const componentRef = createComponent(ValidationErrorsComponent, { environmentInjector });
    appRef.attachView(componentRef.hostView);
  }
}
validation-errors.component.ts
@Component({
template:`
  <val-default-errors>
    <ng-template valError="required" let-label>{{ label || 'This field' }} is required.</ng-template>
  </val-default-errors>
`})
export class ValidationErrorsComponent {}

This code automatically creates our custom ValidationErrorsComponent (which contains html template with default validation errors) and injects it in applicationRef. Any angular project/module that imports this shared module will automatically have default errors, just by importing the module (without having to declare anything in html templates).

But this solutions seems more like a hack. Is there more elegant way?

Hi @jure123

We usually simply add a component to our root component template rather than doing it dynamically, but if your solution fits your needs better, then go with it.

We have chosen to use a template-based approach for errors because we want to be able to support i18n, pipes, html and even angular components or directives in the error messages rather than simply plain text. That's why we don't use a service to configure error messages.