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

Access denied: Unable to rename directory '/usr/local/lib/node_modules/expo-cli' due to permission restrictions

After encountering an error that appeared to be related to permissions, I spent some time troubleshooting and finally found a solution. I wanted to share it here in case it can help others facing the same issue. If anyone has alternative solutions, please ...

Putting an <input/> element inside a Material UI's <TextField/> component in ReactJS - a beginner's guide

I am attempting to style <TextField/> (http://www.material-ui.com/#/components/text-field) to resemble an <input/>. Here is what I have tried: <TextField hintText='Enter username' > <input className="form-control ...

I am attempting to achieve a smooth transition effect by fading in and out the CSS background color using JQuery and AJAX

Can anyone help me with my issue related to using Ajax to fadeIn a background color in beforeSend and fadeOut in success? I seem to have made some mistakes but can't figure out what went wrong. var data={ ...

When an element is set to a fixed position while scrolling, it causes the element to flicker

After implementing the jQuery plugin stickyjs on my website, I noticed a strange issue. While it works perfectly fine on my Mac, when using the mouse scroll wheel on my PC, the element blinks once rapidly as it reaches the top of the page. Interestingly, d ...

Retrieve data from a different div, perform a subtraction operation, and dynamically update yet another div using jQuery

Looking to extract a specific div class value, subtract 500 from it, and display the result in another div. Unclear about the steps needed to show the subtraction outcome on the other div. Consider this scenario: <div class="main-value">6000</d ...

Tips for incorporating fading text and a CTA into your content block

I am looking to protect the full content of my blog posts and allow access only to subscribed members. I want readers to see just a glimpse of the article before it disappears, prompting them to take action with a Call to Action (CTA) like in the fading te ...

What causes the discrepancy in smoothness between the JavaScript animation when offline versus its choppiness when online, particularly on AWS

Recently I delved into game development using HTML5/CSS/JS and embarked on a small project. Check out the game here at this AWS storage link: If you open the game and press SPACE, you'll notice that the ball starts moving with occasional brief pauses ...

Is there a way to eliminate the space between the content inside a table cell and its borders?

I am struggling with a table setup that includes three columns and multiple rows. The first column contains an image, causing the cells in that row to resize based on the image size. When text is added to the 2nd and 3rd columns, it automatically centers w ...

The content has spilled over from the div and leaked into the adjacent div

When the left div's content exceeds the right div's, it spills over into the next container div. Sample HTML: <div class="musictemplate_container"> <div class="musictemplate_left"> something<br> omething< ...

Is it considered a poor practice to share actions between reducers in Angular 2?

Our Angular 2 app utilizes ngrx/store with Reducers like "cameraReducer" and "subjectReducer". We aim to maintain global and common items such as "Loading Data" properties in the "appReducer." In this scenario, is it logical to share an action like {type: ...

We are creating a table in JavaScript and mistakenly adding an unnecessary tbody

I am currently utilizing a combination of plain JavaScript and Jquery in order to dynamically generate a table. The issue arises when I attempt to use a for loop to iterate through the data obtained from an Ajax request, as it fails to create new rows. To ...

What purpose does the # symbol serve in Angular when interpolating values?

Here is an example provided from the following link: https://angular.io/guide/lifecycle-hooks export class PeekABoo implements OnInit { constructor(private logger: LoggerService) { } // Implementing OnInit's `ngOnInit` method ngOnInit() { this ...

Triggering a subsequent action in Ngrx depending on the data from the initial action

Currently, I am fetching a list of users using ngrx: this.users$ = this.store.select(fromReducer.getUsers); In my HTML template: <ul> <li *ngFor="let user of users$ | async"> {{user.id}} - {{user.name}} - {{user.email}} </ ...

Is there a way to initiate a jquery function upon loading the page, while ensuring its continued user interaction?

On my webpage, there is a JavaScript function using jQuery that I want to automatically start when the page loads. At the same time, I want to ensure that users can still interact with this function. This particular function involves selecting a link tha ...

Steps for extracting HTML content from a beautiful soup object

My current situation involves a bs4 object listing: >>> listing <div class="listingHeader"> <h2> .... >>> type(listing) <class 'bs4.element.Tag'> I am aiming to retrieve the raw html as a string. Initially, ...

Flexslider optimized for mobile devices

I am currently using the Sparkling theme on a Wordpress website. This particular theme utilizes Flexslider within a div at the top of the page. Each slide featured in the slider includes an image, as well as a div containing a post title and excerpt. The ...

Display only the div on an iPad screen

Is there a way to show this DIV only on an iPad screen? I've looked around on Google for solutions, but none of them seem to work. It always ends up displaying on my computer as well. Is it possible to make it show only on an iPad screen? @media only ...

What is the best method to adjust the width of the PrimeNG ConfirmDialog widget from a logic perspective

Currently utilizing "primeng": "^11.2.0" and implementing the ConfirmDialog code below this.confirm.confirm({ header: 'Announcement', message: this.userCompany.announcement.promptMsg, acceptLabel: this.userCompany.announcement ...

Angular state correctly maps to the controller but is not reflected in the HTML

I'm currently in the process of setting up a basic Angular application, something I've done many times before. I have defined a home state and another state for a note-taking app, but I am facing an issue where neither state is displaying or inje ...

The $.post method is malfunctioning

I am experiencing an issue where the onchange function is working properly, but the $.post function is not functioning as expected. Below is the HTML code snippet: <input type="checkbox" id="chk" value="3" onchange="checkradio(this.value)"/> Here ...