Header add


In this article we discuss Angular ngFor Directive. Before starting this article please go through the link Angular Directives. In this example we cover below points,
  • What is Angular ngFor Directive ?
  • Example of Angular ngFor Directive ?

What is Angular ngFor Directive ?

The built-in ngFor directive belongs to the Structural directive category. As it belongs to the structural directive category, it is used to change the structure of the DOM.

The ngFor directive is very much similar to the "for loop" used in most of the programming languages. So, the NgFor directive is used to iterate over a collection of data.

The syntax to use ngFor directive is: *ngFor="let <value> of <collection>"

Here, <value> is a variable name and collection is a property on your component which a collection of data. Usually an array but it can be anything that can be iterated over in a for loop.



➤ Example of Angular ngFor Directive

Let us understand ngFor structural directive with an example. Consider the following array of the customers.


Customer List
Fig-1
Then we want to display the above customers list into a table on a web page as shown below. 


Angular ngFor Directive Output
Fig-2
Code Snippet Explanation
  • ngFor directive is used to iterate over a collection. In this example, the collection is an array of customers.
  • ngFor directive is a structural directive, so it is prefixed with * (star). So, the point that you need to remember is, all the structural directive are prefixed with a *.
  • *ngFor='let cust of customers' – In this statement, the 'customer' is called template input variable, which can be accessed by the <tr> element and any of its child elements.
  • The ngIf structural directive displays the row “No Customers to display” when the customer's property does not exist or when there are no customers in the array. 

app.component.ts

Add the customers list into the app.component.ts file like below;


 app.component.css

Add the below CSS into the component like below;

 app.component.html

Add the below HTML to iterate through the customers.

Code Snippet Explanation
  • *ngFor='let cust of customers' – In this statement, the 'customer' is called template input variable, which can be accessed by the <tr> element and any of its child elements.
  • The ngIf structural directive displays the row “No Customers to display” when the customer's property does not exist or when there are no customers in the array. 

Finally, Run the application and see the output like below;







  
  
</> Source Code in Github.com/CoreProgramm/
  Summary
 In this tutorial we discussed Angular ngFor Directive. If have any question related to this topic then give your feedback.

You May Also Like...

Post a Comment

Previous Post Next Post