Angular ngIf directive

testYourself82 0 0

*ngIf is a structural directive that modifies the structure of the DOM. 

It works similarly to the JavaScript if statement. It adds or removes elements depending on the condition. When the ngIf condition is true, the element is rendered, and when the condition is false, it is not rendered at all. It has an asterisk prefix like other structural directives.

<button *ngIf="isLoged" (click)="logout()">Logout</button>

ngIf else

The ngIf directive also supports the else statement. It behaves very similarly to a JavaScript if else statement. Allows you to show different elements when the condition is false.

To use the else statement, We need to add the ng template and assign a template variable using a hash sigh. Template variable allows to create a reference to a DOM element within a template.

<button *ngIf="isLoged; else loggedOut" (click)="logout()">Logout</button>

​​​​​​​<ng-template #loggedOut>
  <button (click)="login()">Log in</button>
</ng-template>

ngIf then

ngIf also allows you to use the then statement. It works the same as a single ngIf, but requires a different HTML structure.

<div *ngIf="isLoged; then loggedIn; else loggedOut"></div>

<ng-template #loggedIn>
  <button (click)="logout()">Logout</button>
</ng-template>

<ng-template #loggedOut>
  <button (click)="login()">Log in</button>
</ng-template>

You can use single then without else and it still works.

<div *ngIf="isLoged; then loggedIn"></div>

<ng-template #loggedIn>
  <button (click)="logout()">Logout</button>
</ng-template>