How can I use the *ngFor directive in Angular 2 or Ionic applications?

I am currently working on an Ionic Project. Upon button click, a request is processed and data is received as shown below:

   public login() {
    //this.showLoading()
    var test33;
    this.auth.login(this.registerCredentials).subscribe(data => {
      console.log(data["_body"])
      test33 = data["_body"]
      console.log(test33)
    },
      error => {
        this.showError(error);
      });
  }

Within the view:

 <ion-row class="logo-row">
        <ion-col></ion-col>
        <h2  *ngFor="let user0 of test33">{{ user0.name }}</h2>
        <ion-col width-67>
          <img src="http://placehold.it/300x200"/>
        </ion-col>
        <ion-col></ion-col>
      </ion-row>`

Upon checking the console, I see that the data is being stored in variable test33 as:

 [{"id":1,"role_id":1,"name":"Dr. Admin","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d0b1b4bdb9be90b1b4bdb9befeb3bfbd">[email protected]</a>","avatar":"\/user\/1\/profile\/HR1-dummy-avater.png","password":"$2y$10$iEpnh6pJ09rxH5NFFCVzaewBCxC\/FHZuHnkWA6qUrOBO3tYIBbsVC","remember_token":"VgwXUdIpL6EqW7Fp66VGRPjSKE727Inc4MTseJQq84cTCglkS335KCqVnavu","created_at":"2017-05-25 22:46:10","updated_at":"2017-06-14 05:19:52","is_feature":null}]

However, {{user0.name}} does not return the name.

Please assist in identifying where my mistake lies.

Answer №1

When using test33 as a variable rather than a property, ngFor cannot access it in the component's properties.

To resolve this issue, you need to declare test33 as a property like this.test33; so that ngFor recognizes it as a property.

Important note: To use variables from your code in the template, they must be declared as component properties.

I hope this explanation helps!

EDIT:

import { Component } from '@angular/core';

@Component({
  selector: 'home-page',
  templateUrl: 'home.html'
})
export class HomePage {

  test33;
  andAnyPropYouWantHere;

  constructor() {}

}

By declaring props like this in the component, you can easily use them with directives like ngFor and ngIf in the template :)

Answer №2

The issue here is that the variable test33 is defined as a local variable, rather than being a property of the component. This means that the view does not have access to its value.

To resolve this, you need to declare test33 as a property of the component:

@Component({
    selector: 'page-home',
    templateUrl: 'home.html'
})
export class HomePage {

    public test33: any;

    //...

}

Then, you can set the value of test33 in the login() method using this.test33:

public login() {
    //this.showLoading()
    // var test33; <- remove this line
    this.auth.login(this.registerCredentials).subscribe(data => {
      console.log(data["_body"])
      this.test33 = data["_body"]
      console.log(this.test33)
    },
      error => {
        this.showError(error);
      });
  }

With these changes, the value should now be accessible in the view as intended.

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

What is the best way to eliminate Bootstrap from an Angular project?

When running my Angular project, I noticed that _reboot.scss is being uploaded and overwriting the styles of Angular Material. I attempted to remove it by following these steps: npm uninstall bootstrap Remove links from package.json Remove links from ang ...

conceal parent window element upon clicking an image within an iframe

I'm facing a challenge with hiding certain buttons in a parent window when opening a modal by clicking an image inside an iframe. Below is the code snippet that I am using: In the parent window - <iframe id="gallery" src="links/gallery.html" wid ...

What is the best way to incorporate a scroll bar into a table that updates dynamically?

If I were to create an empty table in my index.html: <body> <table width="800" border="0" class="my-table"> <tr> </tr> </table> </body> Afterward, I would dynamically add rows and columns to my-table using ...

Properties of a child class are unable to be set from the constructor of the parent class

In my current Next.js project, I am utilizing the following code snippet and experiencing an issue where only n1 is logged: class A { // A: Model constructor(source){ Object.keys(source) .forEach(key => { if(!this[key]){ ...

Creating crypto.createCipheriv arguments from fixed origins

Currently, I am implementing a code snippet in my node.js application to perform string encryption. I am seeking guidance on how to create the KEY and HMAC_KEY from a predetermined source. At the moment, these keys are randomly generated within the progra ...

The select2 option seems to be malfunctioning as it is not

I have implemented a dropdown using Select2. Although I am able to retrieve data from the backend and display it successfully in Select2, I'm facing an issue with certain data that contains multiple spaces between words. For example: Test&nbsp;& ...

JSON data is returned as Object Object

Trying to work with a JSON object and need to stringify it for localStorage: $http.post('http://localhost:8000/refresh', { name: $scope.name, email: $scope.email, token: $rootScope.devToken, platform: ionic.Platform.platform() }).then( ...

What is the best way to update information in the `App` component using Vue?

Within Vue, I have an App component that utilizes the <router-view> to extend the functionality of a Login component. My goal is to update specific data within the App component when a button is clicked in the Login component. Is this type of inter ...

A guide on accessing $bvToast in Vue class components

I am fairly new to vue.js but I have managed to figure out some things. I initially started with regular js, but then transitioned to typescript with class style vue components. For styling the components, I rely on bootstrap-vue. In my main.ts file, I im ...

Concealing specific elements in Angular by utilizing ng-class conditions

Here's the code snippet I am currently working with: <tr ng-repeat="version in allVersions" ng-class="{{ version['active'] == 'true' ? 'active' : 'inactive' }}"> </tr> The ng-class is functioning ...

When trying to link a Redis microservice with NestJS, the application becomes unresponsive

I am attempting to create a basic hybrid app following the guidance provided by Nest's documentation, but I have run into an issue where the app becomes unresponsive without any errors being thrown. main.ts import { NestFactory } from '@nestjs/c ...

Tips for utilizing [(ngModel)] with an object that is empty, null, or undefined in Angular 4

When trying to assign [(ngModel)] inside my .html code to an empty (null or undefined) object, I encountered the error message _co.object is null. There are two scenarios: one where the object has a value and one where it does not. The ngModel works fine i ...

Troubleshooting TypeScript compatibility with SystemJS when encountering problems with the .js extension

Initializing my TypeScript file with the import statement below. It's important to note that the lack of a .ts extension indicates that I am importing a TypeScript module: import githubService from './github.service'; Through transpilation ...

Using importXML with Internet Explorer 11

My project website includes a roster page that retrieves XML data. Previously, this functionality worked across all browsers but now it only works in Chrome. In IE11, it seems that the importXML function is not functioning correctly as the roster data is m ...

When attempting to trigger an error, the unit test will fail to pass

I am relatively new to Mocha, Chai, and Unit Testing. I'm currently attempting to create a basic test to verify the presence of Authorization headers in the request that passes through my middleware function. Despite trying various approaches such as ...

An advanced template system incorporating dynamic scope compilation

My project requires a unique solution that cannot be achieved with standard data-binding methods. I have integrated a leaflet map that I need to bind with a vue view-model. While I was able to display geojson features linked to my view, I am facing chall ...

Enhancing user experience with VideoJS player overlay buttons on mobile devices

I am currently using VideoJs player version 4.2. When I launch a videojs player on Safari browser in an iOS device, it defaults to native controls. However, when I pause the player, overlay buttons (links to navigate to other pages) are displayed on the v ...

Set up ExpressJS to utilize port 3000 for the server

I am working on an app where the backend is currently running on localhost:8000, but I need it to run on port 3000. Specifically, I am using an express server for this example. How can I configure it to run on the desired port? Below is my current server. ...

Accessing the router URL directly is proving to be ineffective

Currently, I am utilizing react-router in my project and everything is functioning perfectly except for when I directly access the URL. Specifically, if I click on a Link within the application that navigates to "/quizreview?quizId=nAUl3DmFlX", it works fl ...

Should I reload the entire table or insert a row manually?

This unique ajax question arises: within a table lies the users' information, displayed based on individual settings and timing. Sometimes, users instantly see the data, other times they must wait for it - their choice determines when it appears. Wha ...