07 Structural Directives 1/2

Maurício Alexandre Barroso
3 min readJul 9, 2021

At this stage of our studies, we will talk about an extremely important subject for those who intend to learn Angular: directives. In the previous article we talked about Attribute Directives and created our own policy. Now in this article we'll look at the *ngfor and *ngIf Structural Directives with a simple and practical example.

The first step we need to take to access the structural directives that Angular provides us is to import the CommonModule module into our app.module.ts file.

NgIf

The *ngIf structural directive is a way to add a conditional to an element of our HTML document so that it is displayed on screen or not based on a conditional. In the base project that we have been using throughout our studies, we will make some adjustments so that we can see in practice how this directive works.

In the first-component.component.html file delete the existing code and replace it with the code below.

In the first-component.component.ts file, delete the functions and variables that we had created in the previous article and replace it with the code below.

Run the ng serve command on your terminal and a few clicks on the button we created and watch the magic happen! =D

NgFor

The *ngFor structural directive allows us to dynamically create elements in the DOM, using for that an array with the information you want to print on screen.

As an example we will make some changes to our first-component again. Replace the current code with the base code.

Run the ng serve command on your terminal and see the power of Angular working in your favor! =D

In these two simple examples we can know these two important features that are extremely useful and indispensable in Angular projects.

Create new conditionals, add some logic, test, debug, practice and study the code we created in this article so that you can fix the knowledge. If you want to deepen your studies, don't forget to search the official documentation for your doubts. Good studies! :)

In the next article we'll talk about some other directives that can be very useful too like ngClass, ngStyles, and… Enough spoiling! >D

--

--