A complete guide on utilizing *ngFor in Angular to display data rows

I am facing an issue with using *ngFor to create new "rows" for adding new categories dynamically.

Although there are no errors displayed when I run the program, the intended functionality is not achieved. I have tried making some modifications but it seems like nothing inside *ngFor is being executed... Can someone provide assistance?

  FetchCategory() {

    var self = this;
    this.Global.refreshToken().subscribe(function (result) {
      self.uploadService.getCategory().then(function (resultado) {

        if (resultado) {

          // self.category = resultado; 
          var categories = JSON.parse(resultado);
         // console.log(categories);

        } else {

        }
      }).catch();
    });
  }

 <div class="bodyPermCardDam">
    <div *ngFor="let category of categories; let i = index">
        <ng-template>
            <div class="categoryChoosedName catParm{{category.ID}}" (click)="SelectCategoryPerm(category.ID,1)">
                <svg class="folder" id="folder{{category.ID}}" xmlns="http://www.w3.org/2000/svg" width="24" height="19.2" viewBox="0 0 24 19.2">
                    <style type="text/css">
                        .folder:hover .stSpecial,
                        .folder:active .stSpecial {
                            fill: #4981C2 !important;
                        }

                        .stSpecial {
                            transition: all 0.3s ease 0s;
                        }
                    </style>
                    <g transform="translate(-32 -92)">
                        <g transform="translate(28 84)">
                            <path class="stSpecial" d="M13.6,8H6.4a2.389,2.389,0,0,0-2.388,2.4L4,24.8a2.4,2.4,0,0,0,2.4,2.4H25.6A2.4,2.4,0,0,0,28,24.8v-12a2.4,2.4,0,0,0-2.4-2.4H16Z" fill="#caced5" />
                        </g>
                    </g>
                </svg> {{category.Name}}
            </div>        
        </ng-template>
    </div>
</div>

Answer №1

Make sure to eliminate the ng-template tag from your code so that it can display results within the *ngFor loop. This is how the <ng-template> element functions.

To properly render the content of the ng-template, you'll need to use a ng-container. Here's a useful resource for more information: Check this out

 <div class="bodyPermCardDam">
    <div *ngFor="let category of categories; let i = index">
            <div class="categoryChoosedName catParm{{category.ID}}" (click)="SelectCategoryPerm(category.ID,1)">
                <svg class="folder" id="folder{{category.ID}}" xmlns="http://www.w3.org/2000/svg" width="24" height="19.2" viewBox="0 0 24 19.2">
                    <style type="text/css">
                        .folder:hover .stSpecial,
                        .folder:active .stSpecial {
                            fill: #4981C2 !important;
                        }

                        .stSpecial {
                            transition: all 0.3s ease 0s;
                        }
                    </style>
                    <g transform="translate(-32 -92)">
                        <g transform="translate(28 84)">
                            <path class="stSpecial" d="M13.6,8H6.4a2.389,2.389,0,0,0-2.388,2.4L4,24.8a2.4,2.4,0,0,0,2.4,2.4H25.6A2.4,2.4,0,0,0,28,24.8v-12a2.4,2.4,0,0,0-2.4-2.4H16Z" fill="#caced5" />
                        </g>
                    </g>
                </svg> {{category.Name}}
            </div>        
    </div>
</div>

Answer №2

To properly display the categories, make sure to define a public list of categories within the component:

public categories: any[];

GetCategory() {
   
   var self = this;
   this.Global.refreshToken().subscribe(function (result) {
       self.uploadService.getCategory().then(function (resultado) {
           if (resultado) {
             this.categories = JSON.parse(resultado);
           } else {
    
           }
       }).catch();
   });
}

Also, ensure you add an *ngIf in the view to wait for the data:

<div class="bodyPermCardDam" *ngIf="categories">
    <div *ngFor="let category of categories; let i = index">
         ...    
    </div>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble with JavaScript's Date.getUTCMilliSeconds() function?

I have a straightforward question for you. Take a look at this Angular App and try to create a new date, then print the number of UTC milliseconds of that date in the console. Can you figure out why it is returning zero? ...

The importance of scope in ng-style

I am attempting to dynamically change the font color in an input field based on the value entered into that field. However, I have encountered an issue with using ng-style as it is not recognizing the value of the scope and therefore the color does not upd ...

"Incorporate countless Bootstrap 4 carousels into one webpage for an enhanced user

I'm experiencing difficulties with the new Bootstrap 4. Can anyone provide guidance on how to incorporate multiple Bootstrap carousels into a single page? I've researched several websites, but most only offer solutions for Bootstrap 3. Your assi ...

Arranging items in a vertical column using CSS based on the content

I am facing an issue with aligning the values in a column under each other without percentages using my own html code, css, and bootstrap classes: <div class="d-flex"> <p class="table-string">91.86</p> <span ...

Ways to verify if a web URL is contained within an HTML textbox

In the process of developing a frontend form for WordPress, I have incorporated a basic HTML textbox for users to input a web URL. My goal now is to ensure that the entered value is indeed a valid URL and not just arbitrary text. Is there a way to perfor ...

How can we convert unpredictable-length JSON user input into well-structured HTML code?

Welcome to the world of web development! I am currently embarking on a project where I aim to transform JSON data into HTML structures. Specifically, I am working on creating a dynamic menu for a restaurant that can be easily updated using a JSON file. The ...

What is the best way to create a method that waits for a POST request to complete?

I have the following code snippet: login() { const body = JSON.stringify({ "usuario":"juanma", "password":"1234"}); console.log(body); let tokencito:string = '' const params = ne ...

What causes my form submission to redirect to a php file instead of staying on the

I'm currently using PHP mailer to send emails with data. The form submission is working perfectly on XAMPP locally, as I receive the email with the specified data after submitting the form. However, when I try running my app on Vercel or Netlify, it ...

Tips for Customizing a Bootstrap input-group to Resemble a form-group

I'm struggling to match the appearance of the last row with the others, but I want to include the icon in the text box. Adjusting the width has been a challenge! (I'm sorry for the inconvenience, the code snippet may not display correctly on thi ...

Changes made to one order's information can impact the information of another order

Currently, I am in the process of developing a unique shopping cart feature where users input a number and a corresponding product is added to a display list. Users have the ability to adjust both the price and quantity of the products, with the total pric ...

"Enhancing Your Website with a Preloader Loading GIF: Step-by-Step Guide

Can anyone assist me in implementing a preloader with a 'loading' gif image on my website that will display for a maximum of 5 seconds before the site fully loads? I've attempted various methods without success, so any help would be greatly ...

Angular: Refresh mat-table with updated data array after applying filter

I have implemented a filter function in my Angular project to display only specific data in a mat-table based on the filter criteria. Within my mat-table, I am providing an array of objects to populate the table. The filtering function I have created loo ...

The Django static files were uncooperative and refused to function

I've encountered an issue with my HTML files while using Django. Some files work perfectly fine when I load static files, but others don't seem to cooperate. I'm perplexed as to why this inconsistency exists! Have I overlooked something impo ...

What is the best way to bridge the gap between the rows?

After combining the top and bottom blocks, I now have a gap in my layout. Is there a way to move this row up without causing any issues? I need assistance with resolving this problem using Bootstrap. <link rel="stylesheet" href="https://maxcdn.boots ...

Exploring the HTML5 File API: Features and Capabilities

After looking into the File API, I'm curious about when all major browsers will fully support it: Firefox has supported it since version 3.6 Chrome since version 8.0 What about Opera and IE? Is the File API meant to replace flash-based uploaders li ...

Challenges arise when working with arrays: Attention required - Offset 0 undefined

I have encountered a challenge with my PHP code. I am attempting to convert an HTML table into an array and then execute a mysqli query, but I am unsure about the process. In my code, I have a variable $aDataTableDetailHTML[][]. The first set of brackets ...

Unit Testing JWT in Angular 2

Using JWT for authentication in my API calls. I am in the process of coding a service method. An interceptor is applied to all requests: public interceptBefore(request: InterceptedRequest): InterceptedRequest { // Modify or obtain information from ...

Displaying an array value instead of a new value list in a React component

Situation - Initial number input in text field - 1 List of Items - 1 6 11 Upon removing 1 from the text field, the list becomes - New List Items - NaN NaN NaN Now, if you input 4 in the field. The updated List Items are - NaN NaN 4 9 14 Expected ...

The combination of Observable streams in combineLatest will persist even if one encounters a

I have a function designed to retrieve multiple documents from Firebase. fetchDocuments(documentIds: string[]): Observable<TreeNodeDocument[]> { const observables = []; for(let id of documentIds){ observables.push(this.fetchDocument( ...

Magnific Popup displaying only the initial item

As someone new to using jQuery and Magnific Popup, I am working on a grid of images. When an image is clicked, I want Magnific Popup to display a specific div containing information relevant to that particular image. <div class="grid"> <div c ...