Angular 2 ngFor directive

We explain the ngFor directive, or *ngFor, which allows us to repeat a block of HTML a number of times in Angular 2 applications.

In this article we are going to learn and practice with one of the most important directives in Angular 2, which is the ngFor directive, capable of repeating elements within the page. This repetition allows us to traverse an array structure and for each of its elements replicate a number of elements in the DOM.

For those who come from Angular 1, it will sound familiar to them, since it is the same as what is already known from ngRepeat, although they change some things about the syntax for the loop expression, as well as some mechanisms such as ordering.

Basic usage of ngFor

To see an example of this directive in operation, we are forced to create an array with data beforehand, which must be sent to the view, so that this repetition can be carried out in the HTML. As everything in Angular 2 is organized by a component, we are going to create a component that contains what is necessary to be able to use this ngFor.

We start with the code of the TypeScript part, which is where we will have to create the data that will be available in the view.

import { Component, OnInit } from ‘@angular/core’; @Component({ moduleId: module.id, selector: ‘app-list-questions’, templateUrl: ‘list-questions.component.html’, styleUrls: }) export class ListQuestionsComponent implements OnInit { questions: string = ; ngOnInit() { } }

This code must sound familiar to us, since it is the boilerplate of a component (created using Angular CLI) to which we have added the declaration of a string array property.

Note: We have assigned the value of that array literally, but you would normally get it from some source like a web service, API, etc.

See also  How to download a manual

Next, let’s look at the HTML for this component, which is where we put the ngFor directive.

{{question}}

It is something very simple, we simply have a paragraph that will be repeated a number of times, one for each element of the questions array. In this case it is a simple paragraph, but if we had more elements inside it, they would also be repeated. What we have to analyze in detail is the use of the directive, although we believe that it is perfectly self-explanatory.

*ngFor=”let question of questions”

The first thing you will see is an asterisk symbol

which might seem a bit strange. It is nothing more than “syntactic sugar” to remind us that these directives (those started by the asterisk) affect the DOM, producing the insertion, manipulation or deletion of its elements.

As a value of the directive you will see that a “question” variable is declared internally for this loop, which will take each of the values ​​of the array as its value in each of its repetitions.

Note: “let” is a way of declaring variables in Javascript ES6. It means that that variable will only be valid within the block where it is declared. In this case “internally” we mean that “question” will only be valid in the label that has the ngFor and any of its child elements.

Traversing arrays with objects with ngFor

Generally, you will use ngFor to go through arrays that will surely have an object as a value in each of its cells. This doesn’t change much from what we’ve already seen in this article, but it’s a nice opportunity to learn something new with TypeScript.

For now let’s see things without TypeScript to go progressively. This would be how the declaration of our array would look, to which we will not yet indicate the type so as not to get confused.

See also  Builders in PHP

questionsObj =

As you can see, what used to be an array of simple strings has become an array of objects. Each of the objects describes both the question itself and the positive and negative responses that have been received so far.

Now, using it in the view, the HTML, we can display all the data for each object, with code that might look something like this:

{{objQuestion.question}}:
Yes {{objQuestion.if}} / No {{objQuestion.no}}

As you can see in this code, within the paragraph I have access to the question, which, being an object, contains various properties that I use to display the complete data of each item.

Modification Implementing TypeScript Interfaces

As you have seen, there is not much difference with respect to what we had, but now we are going to give TypeScript a use that will allow us to experience something that the language gives us: interfaces.

In this case we are going to use the interfaces simply to define a data type for the questions, a schema for our question objects. In this case we are only going to use it so that, when writing code, the editor can help us by indicating errors in case the interface is not fulfilled. Thus, when writing code we can be sure that all the questions with which we work have the data that is necessary for the application.

Note: The interfaces are known to be mechanisms to solve the deficiencies of multiple inheritance, in this case we are going to use them as a simple definition of types.

Something as simple as this:

interface QuestionsInterface { question: string; if: number; not: number; }

Allows TypeScript to learn the schema of a question object. Now, using this interface, you will be able to declare your question array in this way.

See also  Colors and HTML

questionsObj: QuestionsInterface =

Now we are indicating the type of the elements of the array, telling it that it must match what is defined in the interface. You like? Maybe now you don’t notice much difference, but this can be used for several things, meaning help in the development stage, and without affecting the performance of the application, since the interfaces in TypeScript once the code is transpiled do not generate any code in javascript.

Note: Normally you put the interface code in a separate file and do the corresponding “import”. Remembering that Angular CLI has a command to generate interfaces that you may find useful. For now, if you want, you can put it in the same file as the component’s TypeScript code as a test.

It may be difficult for those of you not used to TypeScript to get an exact idea of ​​how the code editor would help you just by using that interface. To illustrate it, we have created this video in which we show the contextual help when we are developing with Visual Studio Code.

We’ll talk more about interfaces on other occasions. Now the objective was simply to see a small sample of the utilities that it could bring us.

As you will have seen, it is not difficult to understand this directive, but keep in mind that we have seen the essentials about repetitions with ngFor. There is much more that should be discussed in the future, about slightly more advanced uses such as the ordering of the elements of the list.

Loading Facebook Comments ...
Loading Disqus Comments ...