The TypeScript docs define enums as follows:
Enums allow us to define a set of named constants. Using enums can make it easier to document intent, or create a set of distinct cases. TypeScript provides both numeric and string-based enums.
An enum can be stored as a single value, but storing a collection of enum values is verbose. Especially if you're using a relational database, for example SQL Server, where you need to create a different table to store these values.
Let's use a selection of weekdays as an example, where a user can select one or more days. In code, we have different structures to store a user's selection:
While these structures work, they aren't optimal when you need to send them to a backend service. To make it easier for us, we can use flagged enums. A flagged enum can be used to efficiently send and store a collection of boolean values.
In a flagged enum, each value of the enum is assigned to a bit value. These must be bit values because each combination possible will be unique. That's why flagged enums are useful, they provide a way to efficiently work with a collection of values.
To work with these values, we make use of bitwise operators.
The first step is to convert the
Days enum to an array of bit numbers.
This gives us the following array we can work with:
It's important to filter out non-numbers values, otherwise the output will look as follows:
A flagged enum is stored as a single value, but our front-end is represented as a checkbox list. To map the user's selection to a single value, we create a sum of the selected values:
If we select monday and wednesday this
formValueToBit function will have 5 as output:
To do the inverse and map the value back to an array of booleans, to determine if a checkbox must be checked or not, we use the bitwise AND operator.
This gives the following result:
Angular form example link
You can play around with an Angular reactive forms implementation:
I appreciate it if you would support me if have you enjoyed this post and found it useful, thank you in advance.