Lesson 7 - More *ngFor

Before we move on to other things, I wanted to come back to one more thing about *ngFor. Knowing this is crucial if you want to complete parts of the card picker exercise, (namely step 3), so I decided to give this its own section.

What can I do with the data inside ngFor?

Lets take a look at an ngFor that loops over the following array:

colors = ['orange', 'yellow', 'purple', 'pink'];

<div *ngFor="let color of colors">

<p>Member of the colors array: {{ color }}</p>

</div>

We've seen this kind of format before. We're looping through the array colors, and assigning the value of each iteration to the variable color. We then use {{ }} to display that variable as part of the p tag. Since there are four items in the array, this div, along with the p tag inside, will be displayed 4 times.

What you may not have known is that you can pass the value of that variable back into your TS. Let's assume we have the following method in our TS:

public exclaimColor(color:string):string {

const result = color.toUpperCase() + '!';

return result;

}

Now we got a method that takes in a string, capitalizes it, and adds an exclamation point. Now we can bind to the result of this method in our HTML while passing in data from our for loop. Behold:

<div *ngFor="let color of colors">

<p>Member of the colors array: {{ exclaimColor(color) }}</p>

</div>

Make sure you wrap your head around this, because it's important. We called the method exclaimColor and passed the value of the color variable that we declared in our loop. This means that we will be calling this method once for each iteration of our array and we are displaying the result of that method. The output looks like this:

Member of the colors array: ORANGE!

Member of the colors array: YELLOW!

Member of the colors array: PURPLE!

Member of the colors array: PINK!

We can also pass the value of the iteration to events such as a click event. Check out the following:

<div *ngFor="let color of colors">

<button (click)="myMethod(color)">{{ color }}</button>

</div>

In this instance, we are creating a set of buttons with our loop, and we are setting a click event to each button that will call the method myMethod and will pass the value of our iteration into the method.

It is quite important to understand this concept; you will need to pass data from an ngFor to complete stage 3 of the card picker exercise. but if you can understand how this is working, you are well on your way to being able to create pages with dynamically loaded content.