However, we can simplify the code even further by taking a section of our code and then applying the ngFor directive to create a loop and repeat it in our page.
Let’s see how it works in code. Open your Angular project on VS Code and go to the app component html page.
Our app will display a list of articles so it will put the title of the article in the head element and the description of the article in the paragraph element.
If we have 3 articles, we would have 3 sets of these elements.
Let’s see how we can use the ngFor directive. Go to the app component TypeScript file and declare an array.
Apply the ngFor directive to the template by using the shorthand syntax and begin writing our loop.
We can use interpolation to get the title and the description by taking the variable an accessing the properties.
The next thing I want to talk about are the exported values that we can find in a ngFor directive. We can use these values to get some information about our elements during the loop.
Lastly, use interpolation to get the value by calling the name that we have given the value.
If we want to access another value, we would put another semi colon and then put another value.
Save the project and go to the browser.
As you can see, it is displaying the index of each element.
©2019 - 2024 Codeible. All rights reserved.