Utilizing string enums allows for the following approach.
A simple definition of my string enum would look like this:
enum StatusEnum {
Published = <any> 'published',
Draft = <any> 'draft'
}
When translated to JavaScript, it resembles the snippet below:
{
Published: "published",
published: "Published",
Draft: "draft",
draft: "Draft"
}
To streamline usage across multiple instances in my project, a utility function was created within a shared service library:
@Injectable()
export class UtilsService {
stringEnumToKeyValue(stringEnum) {
const keyValue = [];
const keys = Object.keys(stringEnum).filter((value, index) => {
return !(index % 2);
});
for (const k of keys) {
keyValue.push({key: k, value: stringEnum[k]});
}
return keyValue;
}
}
To implement this functionality in a component and bind it to the template, utilize the examples below:
In the component:
statusSelect;
constructor(private utils: UtilsService) {
this.statusSelect = this.utils.stringEnumToKeyValue(StatusEnum);
}
In the template:
<option *ngFor="let status of statusSelect" [value]="status.value">
{{status.key}}
</option>
Remember to include the UtilsService in the provider array within your app.module.ts file for easy injection into different components.
As a newcomer to TypeScript, I welcome any corrections or suggestions for improvement.