The ngSwitch
directive is a good alternative to ngIf
if you have to handle more than two scenarios.
It works similarly to a switch
statement in traditional programming languages, allowing you to define a set of cases and associate each case with a specific template block to be rendered. For instance:
One of my favorite use cases is for basic pagination in a component (or an image carousel, for instance) where clicking on navigation buttons changes a value that triggers a different “case”:
Clicking on the buttons changes the value of page
and displays a different template. Applying this to components instead of HTML elements is especially powerful. For instance: <app-hello *ngSwitchCase="3"></app-hello>
You can see an example in action on Stackblitz here.