One way to address that issue is by utilizing pipes. Below is an example of how a pipe can be implemented:
import { Pipe, PipeTransform } from '@angular/core';
import * as constants from "./constants";
type key= keyof typeof constants;
@Pipe({
name: 'constant'
})
export class ConstantPipe implements PipeTransform {
transform(value: any, args:key): any {
return constants[args];
}
}
You can then use the pipe like this :
{{null | constant:'LuckyNumber'}}
UPDATE:
Following @KonradViltersen's suggestion in the comments, considering using value
instead of args
might be beneficial. Another approach involves leveraging the Angular Language Service
.
By changing the type of args
from string
to key
, you can benefit from auto-completion provided by the Language service when dealing with numerous constants. However, adjusting the type of value
to key
will only trigger template errors related to type mismatches without causing runtime issues. Ultimately, it boils down to personal preference.
The problem at hand also pertains to enums.
import * as enums from './enums';
type key = keyof typeof constants;
type enumKey = (keyof typeof enums) ;
@Pipe({
name: 'enum'
})
export class EnumPipe implements PipeTransform {
transform<T extends enumKey, R extends keyof typeof enums[T]>(value: T, args: R): typeof enums[T][R] {
return enums[value][args];
}
}
This can be utilized as follows
{{ 'Complexity' | enum : 'Hard' }}
While autocomplete functionality is available for Hard
, it may not apply to Complexity
Stackblitz