Quick Notes: Use enums instead of string comparisons for *ngIf

Quick Notes: Use enums instead of string comparisons for *ngIf

Make reading code easy on the eyes

As I spend time reviewing code, I have come to realize how important it is to write code that makes it easy for someone else to read. This is especially important when working with HTML templates because it can end up being a lot of lines.

Take a look at the following code:

<div *ngIf="user=='A'">User is Admin</div>
<div *ngIf="user=='O'">User is Owner</div>

This code looks straight forward and innocent enough. However, the developer has to spend time to recall what the values 'O' and 'A' stand for. Furthermore, what if these values were to change in the future? Or, worse, imagine we used these if statements in multiple places within our html template!

Instead, we could do this:

<div *ngIf="user === User.ADMIN">User is Admin</div>
<div *ngIf="user === Users.OWNER">User is Owner</div>

This syntax stands out, and more importantly, we are able to use labels that actually make it easier to read the html template code.

At the end of the day, whenever you find yourself using string within the {{ and }} brackets - think if there is a better way to do that work (maybe using a variable, getter or pipe), or, by using enums.