Have you ever wondered how to bind an enum value or a constant in a template of an Angular component?

Most likely, you have ended up binding a constant like this:

@Component({
  selector: 'app-component',
  template: <app-docs [apiKey]="appSettings.API_KEY"></app-component>`
})
export class Component {
  appSettings = AppSettings;
}

Of course, there is nothing wrong about that, but you will have to repeat this piece of code (appSettings = AppSettings) in every single component where you need your constants.


Even though this is not a primary use-case for a pipe, you can take advantage of them and import them in any template you want, without writing any code in the class of the component.

So, let’s start by creating a couple of enums or constants that make sense for your application:

export const AppSettings = {
  API_KEY: 'key123'
};

export enum DateTimeFormat {
  NG_DATE = 'dd.MM.yyyy',
  NG_TIME = 'HH:mm',
  NG_DATE_TIME = 'dd.MM.yyyy HH:mm'
}

...

Next, we will create a pipe which will export different constants and its values:

@Pipe({
  name: 'constants'
})
export class ConstantsPipe implements PipeTransform {
  public transform(value: string, args?: any): any {
    return {
      appSettings: AppSettings
,
      dateTimeFormats: DateTimeFormat,
      apiRoutes: ApiRoute,
      appRoutes: AppRoute,
      localStorageKeys: LocalStorageKey,
      sessionStorageKeys: SessionStorageKey,
      ...
    };
  }
}

Afterwards, declare a pipe within a module which is shared and use it to bind constants to properties or template itself.

<app-docs [apiKey]="('' | constants).appSettings.API_KEY"></app-component>
...
{{ ('' | constants).appSettings.API_KEY }}

Notice, that we have used empty single quotes as a small hack to provide a value that actually won’t be transformed at all, but since this is a static string, we don’t have to worry about the performance, while this pipe is going to be pure and therefore it will be executed only once.

Furthermore, you can use a pipe within a pipe, which can be especially useful when formatting dates. Take a look at the following example:

<td>
  {{ item.created | date: ('' | constants).dateTimeFormats.NG_DATE_TIME }}
</td>

And the best thing? You can still take advantage of suggestions made by Angular Language Services extension.

So, what do you think, does it help or not? Let me know in the comments 🙂

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *