Angular
Fundamentals of Angular Directives - Structural Directives

NgIf Built-in Structural Directive

PRO
Outline

NgIf

The NgIf structural directive is very commonly used when building applications with Angular. You'll use this to "toggle" whether a host element, and optionally, it's children are displayed in a template.

It's important to note that when using this structural directive that the host element and it's child elements are literally created and destroyed, not just visible or hidden to the user. This comes with both a cost and a benefit. The cost is that the browser and JavaScript engine need to create the elements. This can take some time, especially if you are creating a lot of elements. Most of the time, you don't need to worry about this cost because the benefit far outweighs the cost. The benefit is that when the host element and it's child elements are destroyed, along with all event listeners, the JavaScript engine's garbage collection mechanism can free up memory for your application. This is a good thing.

Here is an example of the NgIf structural directive:

<div *ngIf="loading">
  loading...
</div>

The loading boolean is defined in our component as such:

export class AppComponent {
  loading = true;

    ngOnInit() {
      setTimeout(() => this.loading = false, 1000);
    }
}

The initial value of the loading boolean is set to true, and then after 1,000 milliseconds the value is set to false. This example is very simple, but you get the idea.

Finally, while we are providing an explicit boolean value to the NgIf structural directive you can provide any expression that is evaluated to be either truthy or falsey.

 

I finished! On to the next chapter