Using *ngFor to populate an array in an ion-list within Ionic 2

Hi there, I'm currently learning Ionic 2 and I recently created an array that I want to loop through in an ion-list.

This is my produk.ts

import { Component } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';


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



  constructor(public navCtrl: NavController, public navParams: NavParams) {
    var menu: any[] = [
      "menu 1",
      "menu 2",
      "menu 3"
    ];
  }

}

I attempted using the following code in my HTML file, but unfortunately, it did not work as expected.

<ion-content padding>

  <ion-list>
    <ion-item *ngfor="let item of menu">
     {{menu}}
    </ion-item>  
  </ion-list>

</ion-content>

Answer №1

It is important to establish a class variable.

import { Component } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';


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

   menuList: any[];

  constructor(public navCtrl: NavController, public navParams: NavParams) {
    this.menuList = [
      "menu item 1",
      "menu item 2",
      "menu item 3"
    ];
  }

}

Answer №2

menu must be defined as a class variable in order for the code to function correctly.

export class ProductPage {
 menu: any[] = []; // Start with an empty array to prevent any 'undefined' or 'null' issues with `menu` in the template.
  constructor(public navCtrl: NavController, public navParams: NavParams) {
    this.menu = [
      "menu item 1",
      "menu item 2",
      "menu item 3"
    ];
  }
}

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

Using Typescript to define property types based on their respective values

Is it possible to set a property type based on the property value? For example, if the command is: If 'set' then the payload must be PayloadSet If 'put' then the payload must be PayloadPut If 'del' then the payload must be ...

CSS file not found error: ASP.NET core and Angular unable to locate stylesheet

Recently, I encountered a puzzling issue with my ASP.NET Core web application integrated with Angular. Despite having everything set up properly, the CSS failed to load upon launching the project. Upon inspecting the console, I was faced with this error me ...

How can one change the data type specified in an interface in TypeScript?

I am currently diving into TypeScript and looking to integrate it into my React Native application. Imagine having a component structured like this: interface Props { name: string; onChangeText: (args: { name: string; value: string }) => void; s ...

An unhandled promise rejection occurred because no routes could be found to match. URL Segment:

I'm facing an issue with my application where it doesn't recognize the route even though I have defined and imported it in app.module. Whenever I try to redirect to a specific route upon data retrieval, I encounter this exception: onSubmit(){ ...

While Typescript has the ability to infer recursive functions, it unfortunately cannot infer recursive types

Typescript has the ability to automatically determine the type of a recursive function: /** * Typescript correctly infers the type as * * const referencesSelf: () => ... * * This indicates recursion within the function */ const referencesSelf = () ...

"This error message states that the use of an import statement outside a module is not allowed

After searching for a solution without any luck, I decided to start a new discussion on this topic. Currently, I am working on azure functions using Typescript and encountering the following error: import { Entity, BaseEntity, PrimaryColumn, Column, Many ...

Is data binding not functioning properly in Angular 8?

This query has been raised multiple times in the past and I have reviewed all the suggested solutions. However, I am encountering a common issue - how to retrieve data from the parent component to the child component. I'm unsure of where I'm goin ...

Error in Angular: Trying to access the property 'id' of an undefined value

I am facing an issue with a div tag in my HTML file. The code snippet looks like this: <div *ngIf="chat.asReceiver.id != user?.id; else otherParty"> Unfortunately, it always returns the following error: ERROR TypeError: Cannot read propert ...

I am struggling to make the map method display the specific components I need

Attempting to create a scalable Custom Form using an array of objects and a custom Input field in a React-Typescript project import React, { ChangeEvent } from "react" import { InputField } from "./InputField" interface FormItem { ...

A static method written in Typescript within an abstract class for generating a new instance of the class itself

Imagine I have abstract class Foo { } class Bar1 extends Foo { constructor(someVar) { ... } } class Bar2 extends Foo { constructor(someVar) { ... } } I want to create a static method that generates an instance of the final class (all construct ...

Transcompiling TypeScript for Node.js

I'm in the process of developing a Node project using Typescript, and I've configured the target option to es6 in my tsconfig.json file. Although Node version 8 does support the async/await syntax, Typescript automatically converts it to a gener ...

tsc is not recognizing the configurations in my tsconfig.json file

Running tsc in my project's directory is causing an error to be outputted (as shown below). This is my first attempt at using TypeScript and Node.js. Please consider me as a complete beginner. Operating system: Ubuntu 15.10 64bits NPM version: 2.4. ...

Learn how to effortlessly move a file into a drag-and-drop area on a web page with Playwright

I am currently working with a drag-zone input element to upload files, and I am seeking a way to replicate this action using Playwright and TypeScript. I have the requirement to upload a variety of file types including txt, json, png. https://i.stack.img ...

What steps should I take to resolve the issue where Angular project error states that the data path "/polyfills" must be a string?

I am struggling with deploying my Angular app to Firebase and/or running it successfully locally using NodeJS version 18. To access the package.json and source code, you can click on this link: https://github.com/anshumankmr/jovian-genai-hackathon/blob/mas ...

What is the reason behind having to refresh the page or switch to another tab for the field to display?

Currently, I am in the final stages of completing my update form. However, I am facing an issue with the conditional field. The select field should display a conditional field based on the selected value. The problem I'm encountering is that I need to ...

ESLint warning: Potentially risky assignment of an undetermined data type and hazardous invocation of an undetermined data type value

Review this test code: import { isHtmlLinkDescriptor } from '@remix-run/react/links' import invariant from 'tiny-invariant' import { links } from '~/root' it('should return a rel=stylesheet', () => { const resp ...

How can I adjust the column width in OfficeGen?

Currently, I am utilizing officeGen for the purpose of generating word documents. <sup> let table = [ [ { val: "TT", fontFamily: "Times New Roman", }, { val: "Ten hang", ...

Utilizing Angular CLI configuration for End-to-End testing purposes

I'm currently in the process of updating an Angular CLI project to version 6 The issue I'm facing is that prior to version 6, I could run the command ng e2e -e=e2e and the tests would execute smoothly with the specified environment. However, in ...

Is there a RxJS equivalent of tap that disregards notification type?

Typically, a tap pipe is used for side effects like logging. In this scenario, the goal is simply to set the isLoading property to false. However, it's important that this action occurs regardless of whether the notification type is next or error. Thi ...

What is the best way for me to determine the average number of likes on a post?

I have a Post model with various fields such as author, content, views, likedBy, tags, and comments. model Post { createdAt DateTime @default(now()) updatedAt DateTime @updatedAt id String @id @default(cuid()) author U ...