Friday 26 May 2023

How to use ngFor in a tag? Examples

In Angular, you can use the ngFor directive to iterate over a collection of items and generate dynamic content within an HTML tag. The ngFor directive allows you to loop through an array or an iterable object and create multiple instances of a specified HTML template.

Here's an example of how to use ngFor in a <ul> tag to display a list of items:

html
<ul> <li *ngFor="let item of items">{{ item }}</li> </ul>

In the above example, items is an array or iterable object in the component class that contains the items to be displayed in the list. The *ngFor directive is placed on the <li> tag, and the let item of items syntax defines the iteration. The item variable represents the current item in the iteration, and items is the array or iterable being looped over.

To illustrate the output of the above example, let's assume the component class has the following items array:
typescript
export class MyComponent { items: string[] = ['Apple', 'Banana', 'Orange']; }

When the above code is rendered, the <ul> tag with the *ngFor directive will generate a list with three <li> tags, each containing one item from the `items` array:

html
<ul> <li>Apple</li> <li>Banana</li> <li>Orange</li> </ul>

Assuming the items array in the component class contains ['Apple', 'Banana', 'Orange'], the browser will render the following output:

Apple
Banana
Orange

By utilizing ngFor, you can dynamically generate HTML content based on the items in an array or iterable object, allowing you to create lists, tables, or any other repeating elements in your Angular templates.

No comments:

Post a Comment

Seven front-end development trends in 2023-2024

With the increasing prevalence of apps in the digital landscape , the role of front-end developers remains essential. While apps aim to ove...

Popular Posts