How to Use ngFor Directive in Angular

The ngFor directive in Angular is used to dynamically repeat data within a template, similar to a for loop in JavaScript. It allows you to iterate over arrays and display the data in the HTML. Follow these easy steps to learn how to use ngFor in Angular.

Step 1: Add Data to the HomeComponent

First, you’ll add an array of housing data to the HomeComponent. This will provide the data that ngFor will iterate over.

What to do:

  1. Open src/app/home/home.component.ts.
  2. Remove the existing housingLocation property in the HomeComponent class.
  3. Replace it with a new property called housingLocationList and update it with the following data:
export class HomeComponent {
  readonly baseUrl = 'https://angular.io/assets/images/tutorials/faa';

  housingLocationList: HousingLocation[] = [
    {
      id: 0,
      name: 'Acme Fresh Start Housing',
      city: 'Chicago',
      state: 'IL',
      photo: `${this.baseUrl}/bernard-hermant-CLKGGwIBTaY-unsplash.jpg`,
      availableUnits: 4,
      wifi: true,
      laundry: true
    },
    // Add more housing entries here as shown in the example...
  ];
}

Now, you have an array of housing data ready to display in your template.

Step 2: Use ngFor to Display Data in the Template

Now that you have the data in place, it’s time to display it in the template using the ngFor directive.

What to do:

  1. Open the template file for HomeComponent.
  2. Modify the <app-housing-location> tag to use ngFor like this:
<app-housing-location
  *ngFor="let housingLocation of housingLocationList"
  [housingLocation]="housingLocation">
</app-housing-location>

Here, *ngFor iterates over each item in housingLocationList and assigns it to the variable housingLocation. This value is then passed to the app-housing-location component.

Step 3: Save and Test

  1. Save all the changes you made.
  2. Refresh your browser to see a list of housing locations displayed dynamically on the screen.

You’ve successfully used the ngFor directive to dynamically render a list of housing locations in your Angular app. This is a powerful way to display data that comes from an array or other data sources in Angular templates.

By following these simple steps, you’ve made your Angular app more dynamic and efficient!

Keep Learning 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *