Retrieve data from every iteration of *ngFor in Ionic 4, Ionic 5, and Ionic 6

I am currently working on the following code snippet:

<ion-item *ngFor="let box of boxes">

This code will display results pulled from an array. Check it out https://i.sstatic.net/CK0OV.png

In my .ts file, I have defined the following:

isApproved : boolean;
public box: any;

The boxes array will generate the items in the following format:

  • box1 -> [id, name, isApproved]
  • box2 -> [id, name, isApproved]
  • box3 ->[id, name, isApproved]

I need to access the isApproved value for each box so that when I toggle a switch, it will reflect on the database.

You can visit this link for reference: https://i.sstatic.net/vaMFe.png

Although there is a method to extract the id by clicking and using the route, it doesn't meet my requirements as I prefer opening a new page for this action.

Answer №1

To implement two-way data binding in an ion-toggle, simply use the ngModel directive:

html:

<ion-item *ngFor="let box of boxes">
  <ion-avatar slot="start"></ion-avatar>
  <ion-label>...</ion-label>
  <ion-toggle [(ngModel)]="box.isApproved" (ionChange)="approvedToggled($event)"></ion-toggle>
</ion-item>

ts:

approvedToggled(event, box) {
   if(event.detail.value) {
      // Save box information to the database
   }
   /* or:
   if(item.isApproved) {
     // Save information to the database
   }
   */
}

Answer №2

The solution provided is straightforward. Here is the working code:

For my HTML file:

<div *ngFor="let box of boxes"> 

        <ion-item-sliding id="anyId">
          <ion-item>
            <ion-avatar slot="start">
              <img [offset]="100" [alt]="box.user?.name"
                defaultImage="./assets/img/photo.png" [lazyLoad]="box.user?.photo?.url()" />
            </ion-avatar>
            <ion-label class="ion-text-wrap">

              <ion-text color="dark">
                <h3 class="bold no-margin">
                  {{ box.user?.name }}
                </h3>
              </ion-text>
            </ion-label>
           
          </ion-item>
      
          <ion-item-options side="end">
            <ion-item-option color="primary" (click)="onDelete(box)">
              <ion-icon slot="icon-only" name="trash"></ion-icon>
            </ion-item-option>
          </ion-item-options>
        </ion-item-sliding>
    </div>

In my TypeScript file, I have:

Importing the service:

import { Box } from '../../services/box-service';

Before the constructor:

  public boxes: Box[] = [];
  public box: Box;

constructor(private BoxService: Box) {
    super(injector);
  }

Loading boxes from the service:

  async loadDataFromService() {
    try {

      const boxes = await this.boxService.loadBoxes(this.params);
      for (let box of boxes) {
        this.boxes.push(box);
      }
      
      this.onRefreshComplete(boxes);

    } catch {
    }
  }

...this will return an array with arrays. Each array contains an object.

We can access each box from HTML using (click)="onDelete(box)"

  async onDelete(box: Box) {

      await Swal.fire({
        title: 'Are you sure?',
        text: 'Blah, blah',
        icon: 'warning',
        iconColor: '#5038de',
        showCancelButton: true,
        confirmButtonColor: '#5038de',
        cancelButtonColor: '#e0b500',
        confirmButtonText: 'Yes',
        cancelButtonText: 'No',
        heightAuto: false,
        showClass: {
          popup: 'animated fade-in'
        },
        hideClass: {
          popup: 'animated fade-out'
        }
      }).then(async (result) => {
        if (result.value) {
          await this.boxService.deleteBox(box)
          this.goTo()
        } else {
          this.goTo()
        }
      });

    }
  }

To summarize, the solution for:

<ion-item *ngFor="let box of boxes">
  <ion-avatar slot="start"></ion-avatar>
  <ion-label>...</ion-label>
  <ion-toggle (ionChange)="myFunction(box)"></ion-toggle>
</ion-item>

is simply to use (ionChange)="myFunction(box)" or (click)="myFunction(box)"

In my scenario, box represents the entire object, so passing the id would suffice to execute any action.

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

Dealing with a problem when using ng-repeat in Angular to generate a dynamic

I am using ng-repeat to populate all the necessary rows, but I am encountering an issue with differentiating between each row in terms of user input. Currently, when a checkbox is selected in one row, it gets selected in all others as well. I feel like I ...

How come Typescript claims that X could potentially be undefined within useMemo, even though it has already been defined and cannot be undefined at this stage

I am facing an issue with the following code snippet: const productsWithAddonPrice = useMemo(() => { const addonsPrice = addonsSelected .map(id => { if (addons === undefined) { return 0} return addons.find(addon => addo ...

Tips for converting numerical values in a JSON object to strings within a TypeScript interface

{ "id": 13, "name": "horst", } in order to interface A { id: string; name: string; } When converting JSON data of type A to an object, I expected the conversion of id from number to string to happen automatically. However, it doesn' ...

Experimenting with retrieving input from other components while implementing setTimeout

In continuation of the previous question (linked here), I am still working on tutorials for Angular testing using the same files. The current issue revolves around the setTimeout function. Within both ngOnInit and ngAfterViewInit, I have included a setTim ...

The variables declared within the Promise constructor are being identified as undefined by Typescript

In my code, I am creating a let variable named resolver which I intend to set within a promise constructor function. interface Request { ids: string[]; resolver: () => void; promise: Promise<unknown> } class Foo { public requests: ...

What is the best way to automatically return to the first tab in a modal popup after closing it?

<!-- Small modal --> <button class="btn btn-primary" data-toggle="modal" data-target="#myModal"> Contact modal</button> <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-h ...

Display infobox within agm-marker-cluster

When trying to open the infoWindow inner agm-marker-cluster, I encountered an error message: Cannot read property 'then' of undefined This error occurred in the following line of code: return _this._markerManager.getNativeMarker(infoWindow.hos ...

What is the best way to switch routes in redux saga upon successful login?

Greetings! I'm a newcomer to React and I've been using React hooks and redux-saga for my project. I have a requirement where I need the router to navigate to /home upon successful login. I attempted to achieve this using connected-react-router an ...

Making dynamic changes to AngularJS directive templates during runtime

In my quest to create an input directive that can handle multiple types of inputs (such as Interval (min-max), DateTime, Number, Text...), I've encountered a challenge. It's crucial that when the user changes the data type, the corresponding inpu ...

Attempting to retrieve children records from Firebase

Currently working through the angular-fire-seed tutorial and delving into messages and child posts. Strangely, I am facing an issue where I cannot see the children when attempting to display them directly, yet they are visible when expanding the parent nod ...

Angular JS Sorting Wordpress Plugin allows users to easily organize and sort content

Seeking some assistance here, any help would be greatly appreciated. Currently using a Wordpress Angular JS plugin that is causing some unusual alphabetical sorting. This snippet of code showcases the taxonomy: <!-- for taxonomy --> <div ng-if ...

Troubleshooting: AngularJS 1.5 - Issue with ui-router when attempting to call a component within a state with no parent being recognized

Using angularJs 1.5 has posed a challenge for me. The issue I am facing is that when I attempt to call a state with a component, it does not seem to work. The TemplateURL does not load and I am unsure of what mistake I may be making. Below is the code sni ...

Trigger the browser to refresh translation files following the deployment

Our Angular/Ionic app utilizes the ngx-translate/core package for translations, and is hosted on Firebase. With each new build and deployment, Angular automatically creates a hash for our js files to ensure the browser fetches the latest version when chang ...

Regular expression used for validating postcodes in AngularJS version 1.1.5

I'm having trouble getting the ng-pattern to work with any postcode regex in my code. I've tested a few simple regex patterns and they work fine. The regex patterns I've tried are from the UK Postcode Regex (Comprehensive) page. For exampl ...

Unable to access external library using browserify and debowerify

I'm facing a dilemma with my current setup as I'm dealing with a headache. Here's how things are currently configured: Utilizing bower to acquire vendor libraries (specifically angular) Executing gulp tasks to run browserify Implementing d ...

The Sharepoint web part or react app is encountering an error where it is unable to find the property 'show' within the type 'Readonly<{}>'

I haven't worked with React in a while, especially not in sharepoint. I used the yeoman generator to create a basic react app and now I'm struggling to connect the state. The code below is throwing this error: Property 'show' does not ...

Tips on making a forced call to `super.ngOnDestroy`

I am utilizing an abstract class to prevent redundant code for unsubscribing observables. Here is what it looks like: export abstract class SubscriptionManagmentDirective implements OnDestroy { componetDestroyed = new Subject<void>() constructor ...

Check the type of a conditional parameter

Why isn't this code functioning properly? Could it be a case where Typescript overlooks that a variable of type (T extends '1' ? '1' : never) will never be false, making NonFalse<TypeWithCondition<T>> exactly the same ...

typescript resolving issues with Google Maps API

Currently, I am diving into typescript through a comprehensive Udemy course. Recently, I completed an exercise that incorporated the use of Google Maps. Following that, I made some updates to my Node.js version to 16 using nvm. Subsequently, after updatin ...

Combining server-side and client-side routing in AngularJS: A comprehensive guide

Currently, I am in the process of transitioning a project to an Angular-based Single Page Application (SPA). The project is originally built using node/locomotivejs and serves templates from the server side. Due to its large size, we are converting it to A ...