In this blog we will explore how to use ngIf with “Else” statement and “Then”.
In the above example, the container div will only be shown to the logged-in user, otherwise, the whole content of the div will be invisible.
The button inside the container will be visible only if the user is an administrator.
If there is no container available for the section that we want to hide or show, we can use the ng-container as a directive instead of creating a div merely to apply ngIf. This will show or hide content without creating an extra div.
Hiding elements using CSS:
With ngIf, if we hide an element, then that element does not exist on the page, meaning if we inspect the page using chrome dev tools, you won’t find any HTML element present in the DOM. Instead you will find a strange-looking element like below, if you apply ngIf directive:
The above comments are just for debugging purposes. It helps us in identifying the position of missing elements.
If we use display or visibility CSS properties, the HTML element will be hidden in the page, but when we inspect using chrome dev tools the elements will be visible in DOM .
Along with booleans, we can also pass strings, arrays, objects, and more.
Else part will point to template reference. If emp.length condition is false, then #noEmp template will be initiated and applied to the page, right where ngIf directive was applied. If emp.length is true, then noEmp template will never be initiated and won’t be present in the page.
ngIf then else :