The Built-in `NgFor` Directive

The NgFor directive is structural, which means it changes the DOM. Similar to the previous directives, this is another way of implementing a very popular concept—the for loop in HTML.

The NgFor core directive is extremely powerful when it comes to rendering a list of elements in Angular. So, whenever we have an array with elements that need to rendering, the NgFor is perfect for this job.

The NgFor syntax

We simply have to provide an HTML block that tells Angular how to render a single item, and the directive then adds that element multiple times into the DOM on render time.

The syntax for the basic use case is straightforward to implement and remember:

<div *ngFor="let item of elements">...</div>

We can set the directive on any element that we want to render in the list. For instance, let’s say we want to render an array of fruits, stored as a component’s property:

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
})
export class AppComponent {
  fruits = ['🍎', '🍐', '🍌', '🍉', '🍓', '🥥'];
}

In the template, we can simply use the ngFor directive to render the DOM element for each fruit independently, and use text interpolation {{}} to display this emoji:

<ul>
    <li *ngFor="let fruit of fruits">{{ fruit }}</li>
</ul>

The result is a list of emojis.

Get hands-on with 1200+ tech skills courses.