Using ngFor loop

Author: Dawid Adach

-

1. Initial events list

Since the Event component receives information like the date or title from the App (parent) component, it is now the App component which will be responsible for storing and managing list of events. Let's add an initial list of the events into the app.component.ts


import { Component } from "@angular/core";

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.scss"]
})
export class AppComponent {
  events: Array<any> = [
    {time: '08:00', subject: 'Breakfast with Simon', location: 'Lounge Caffe', description: 'Discuss Q3 targets'},
    {time: '08:30', subject: 'Daily Standup Meeting (recurring)', location: 'Warsaw Spire Office'},
    {time: '09:00', subject: 'Call with HRs'},
    {time: '12:00', subject: 'Lunch with Timmoty', location: 'Canteen', description: 'Project evalutation ile declaring a variable and using an if statement is a fine way to conditionally render a component, sometimes you might want to use a'},
  ];
}
  

Now when we have our initial data, let's learn how to use for loop to dynamically generate all event from events[] array.

2. *ngFor

Angular allows us to variety of usefull directive. On on the most basic and common is ngFor which is a implementation of for loop.

ngFor is designed work with the collections. Since we have collection of events let's see how to use ngFor directive in our code. Update app.component.html with the following code:


      <ul>
        <li *ngFor="let event of events; let i = index">
          {{ i }} {{ event.subject }}
        </li>
      </ul>
  
Preview

As you can see, it's very intuitive. We are browsing through events collection and reffering single instance as event. We have also defined our autoincremented index as i.

Of course names can be adjusted to our variables and convention i.e.:


        <li *ngFor="let item of items; let counter = index">
  

We can also put more complex structure within our loop (i.e. surrounding div, headings etc.):


<ul>
  <li *ngFor="let event of events; let i = index">
    <div class="someClass">
     <h3>{{ i }} {{ event.subject }} </h3>
    </div>
  </li>
</ul>
  
Preview

3. <ng-container>

As you probably noticed ngFor directive is used inside the HTML tags like <li>.

This means that given tag will be duplicated as many times as our loop will iterate. Sometimes you may want to use ngFor loop outside the tag (don't want any element to be repeated).

Although it is impossible to use ngFor directive outside the tag, there is another way. We can use special Angular tag :


  <ng-container *ngFor="let event of events; let i = index">
     {{ i }} {{ event.subject }} 
  </ng-container>
  

This will not render any wraping element around our elements.

4. ngFor vs *ngFor

You also may noticed that we are using a asterisk (*) before the ngFor directive.

It is related to so called templates within Angular. We will learn more about them in a future lesson. For now just remember that:

  • Both ngFor and *ngFor are valid Angular directives
  • *ngFor is simplified version of ngFor which allows us to use it directly on elements like <li>

If you are curious what are the difference, have a look at following code. This:


<ng-container  *ngFor="let item of items; let i = index">
  {{ i }} {{ item }}
</ng-container >

  

is a shorter version of:


<ng-template ngFor let-item="$implicit" [ngForOf]="items" let-i="index">
    {{i}} {{item}}
  </ng-template>
  

Therefore, before we will get to the lesson about Angular templates, keep in mind to rather use asterix if you wan't to avoid issues.

5. Using ngFor to pass events

Now when we know how ngFor works, let's use it to pass dynamically list of all events and render them:


<div class="container">
  <div class="row">
    <div class="col-md-9">
      <div *ngFor="let event of events">
        <app-event [value]="event"></app-event>
      </div>
    </div>
    <div class="col-md-3"></div>
  </div>
</div>


  

Note:
We skipped the index (iterator) part on purpose. We don't need to reffer to it within our loop, therefore we haven't defined a variable for it.

Preview

Rate this lesson

Previous lesson Next lesson

Spread the word:
Do you need help? Use our support forum

About the author

Dawid Adach
For more than 5 years Dawid worked as an IT Consultant specializing in SOA/EAI/ESB in the banking domain. He gained experience working in countries like Netherlands, Belgium, Poland and India developing enterprise-class systems for the most prestigious companies. Since co-founding mdbootstrap.com & brandflow.net in 2016 he has been using and teaching technologies such as Angular, TypeScript, PHP, AJAX, Mongo, SQL, Hadoop Stack, Virtualization, Automation and many others...

Install MDB CLI
It's the fastest way to create and host MDB projects
Free Download

Sign up to follow your progress and get additional benefits