When writing HTML with Angular directives and conditionals, it is important to keep the HTML markup as simple and concise as possible. An HTML file with too much Angular verbosity will be very difficult to read and maintain. By taking full advantage of the right Angular features, we can keep our HTML verbosity to a minumum. One such feature is the ngSwitch directive, which allows us to use switch statements directly within our HTML. In this article, we'll introduce that directive, discuss how to implement it, show some code examples, and compare it to alternative methods.
In the code below, we'll show an example switch case in TypeScript, then the corresponding ngSwitch case:
Notice the syntax difference between the
*ngSwitchCase. This syntax must be observed and correctly implemented in order for the ngSwitch to properly render. Otherwise, the switch will silently fail with no errors thrown or logged.
Comparison: ngSwitch vs ngIf
NgSwitch provides a cleaner and more concise way for conditionally rendering elements as opposed to using *ngIf statements. In the code below, we'll make a comparison between the two to exemplify the point:
Each ngIf statement is more verbose than its corresponding ngSwitchCase statement. The default case is the worst part, as we need to check if it is not any of the other conditions manually. We could avoid that by using ng-templates with else statements inside of the ngIf statements, but this would be even more verbose.
Hard Coded Strings within Switch Statements
A possible source of confusion when providing *ngSwitchCase values: hard-coded strings must be enclosed in their own quotes. When the ngSwitchCase is provided a value, it will consider it to be a piece of code; thus, it will treat what you provide as a variable. If a hard-coded string is provided without being encased in double quotes, Angular will look for a variable with that name and fail to build if there is no variable with that name. The same applies to [ngSwitch] itself.