Using Ionic4 and Angular to create ion-select dynamically within *ngFor loop inadvertently causes all ion-select-options to be linked together

I am looking to dynamically generate a list of ion-select elements based on an array within an object named myObject.array.

  • When I attempt to create this list using mypage.page.ts and mypage.page.html, all my ion-select-options end up interconnected - changing one select option to Y causes all other selects to also change to Y.
  • In the console log, I notice that the ionChange event is triggered only once - however, the data displayed indicates that only a single item within myObject.array has been modified.
  • The issue lies in the fact that the user interface does not accurately reflect the data stored in mypage.page.ts.

The image below illustrates the UI after modifying just one ion-select, along with the discrepancies between the console log and the UI:

https://i.sstatic.net/WdBXa.png

How can I dynamically generate independent ion-selects from an array without linking them together?

Edit:

  • The errors appearing in the console are related to cookies, displaying the following message:
    Indicate whether to send a cookie in a cross-site request by specifying its SameSite attribute
    .
  • These errors are not caused by my code; regardless of adding or removing the page, they persist.

Below is my code snippet:

<ion-header>
  <ion-toolbar>
    <ion-title>mypage</ion-title>
  </ion-toolbar>
</ion-header>

<ion-content>
  <ion-item *ngFor="let output of myObject.array;let i=index;">
    <ion-label> Array object {{i}}</ion-label>
      <ion-select
      [(ngModel)]="myObject.array[i]"
      (ionChange)="change($event, i)"
      okText="Set" cancelText="Throw away">
        <ion-select-option value="Y"> Yes? </ion-select-option>
        <ion-select-option value="N"> No? </ion-select-option>
      </ion-select>
  </ion-item>
</ion-content>

Additionally, here is the corresponding mypage.page.ts code:

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

@Component({
  selector: 'app-mypage',
  templateUrl: './mypage.page.html',
  styleUrls: ['./mypage.page.scss'],
})
export class MypagePage implements OnInit {

  myObject = {array: ['Y','Y','Y']};

  constructor() {
  }

  ngOnInit() {
  }

  change(event, i){
    console.log(event);
    console.log(i);
    console.log(this.myObject);
  }

Answer №1

trackBy is a feature designed to enhance change detection performance.

Just so you know, here's how you can use "trackBy" with an index:

Updating the Template

<ion-item *ngFor="let item of myItems; let i=index; trackBy:indexTracker;">

Adjusting the Controller

indexTracker(index: number, item: any) {
    return index;
}

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 organize JavaScript code for handling multiple variables from multiple form elements while also preserving the selected choices?

For instance, suppose I have an HTML form like this: <form role="search" method="get" id="searchform" action="" > <!-- DIRECT SEARCH INPUT TO SEARCH STRING --> <input type="text" value="" name="s" id="s" /> <input type=" ...

how to use jquery to indicate that a checkbox is selected

click here to see the image $(document).ready(function() { $('.editbtn').on('click', function(){ $('#editmodal').modal('show'); $tr=$(this).closest('tr'); var da ...

What sets apart `npm install --save-dev gulp-uglify` from `npm install gulp-uglify`?

I'm feeling perplexed regarding the npm installation process. Based on what I've gathered, there are several options available to me when installing modules: The -g option which saves modules globally --save-dev No arguments. Could someone cl ...

"Enjoying the convenience of a stationary header while browsing on your smartphone

Hey there! I'm currently facing an issue with my website's fixed horizontal nav bar when zooming in on a mobile device. After doing some research, it seems the only solution is to implement some javascript. I came across a jquery fix (see below) ...

Arranging an Array of Objects in JavaScript by dual criteria

In my JavaScript code, I have an object structured like this: myArray[0] -> 0:"62", 1:8, 2:0, 3:"11" myArray[1] -> 0:"62", 1:8, 2:0, 3:"15" myArray[2] -> 0:"48", 1:8, 2:0, 3:"04" myArray[3] -> 0:"48", 1:8, 2:0, 3:"01" myArray[4] -> 0:"62", ...

Issue with saving images from Ionic App on WCF Service

Having an issue with saving images correctly in my WCF Service when uploading through Ionic application. The image is being saved as invalid. [OperationContract] [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBod ...

What encoding does Algolia utilize to determine the size of a JSON entry - ASCII or UTF-8?

The FAQ document from Algolia states that the maximum size of an entry should be a minified JSON size of 10KB. However, it does not specify whether the JSON string should be ASCII or UTF-8 encoded, which makes it challenging to accurately calculate the siz ...

How can the first paragraph value of a div be found using jQuery in Next.js?

How can I retrieve the value of the first <p> tag within my div when a button inside the same div is clicked? Despite attempting to use $(this), it doesn't appear to be functioning as expected. Take a look at the code snippet below: <div cla ...

Is there a way to dynamically create a Vue component for every tier of a nested JSON object without prior knowledge of the total number of tiers available?

I am working with JSON data that includes a list of retailers, some of which have subretailers that go multiple levels deep. My goal is to use Vue to generate markup that will show the parent retailer along with any nested subretailers underneath it, simi ...

How can one retrieve the selected value from a dropdown menu in Angular?

Objective: My goal is to create a dropdown menu where users can select a value, which will then dynamically change the address of the website based on their selection. Issue: Although I managed to make the address change upon selection, it did so for ever ...

Issues with EventListeners in Internet Explorer

Similar Inquiry: Issue with MSIE and addEventListener in JavaScript? I am currently attempting to detect a close event on a popup window created by the parent page. The objective is for users to fill out a form and then, via a popup window, grant perm ...

Determining season goals for teams using nested JSON data

Is it possible to retrieve a team's total goals scored for the season from the provided data by using the team's name as the input for a function? Would it be accurate to attempt mapping over the rounds and filtering matches where either team1 o ...

Detecting a click on the background div in Angular without capturing clicks on child divs

Over at ollynural.github.io, I've been working on creating a pop-up div in the portfolio page that provides additional information about the project you select. To close the pop-up, I have implemented an ng-click feature so that clicking on the main p ...

Unable to Update the Status Code

When it comes to setting the status code to 9999, I am utilizing the basic Response.StatusCode. In this case, the page is accessed via an AJAX call and the status code is checked at readyState = 4. On detecting 9999 as the status code, an alert pops up wit ...

Sending a result back to a Silverlight user control from a slightly intricate JavaScript function

I am working on a Silverlight user control that contains a textbox and a button. Within this Silverlight page, there can be multiple instances of these user controls. My goal is to have a JavaScript function trigger when the button is clicked. This functi ...

React: encountering issues with accessing component props after page refresh

Whenever I try to reload the 'details' page (not the homepage) on my app, I encounter the following error: "TypeError: Cannot destructure property 'flag' of 'country' as it is undefined." It seems that the data is ...

How to choose a single checkbox in Ionic 2 and retrieve its value

On my single screen, I have about 20 questions and answers retrieved from a database. To display the options, I am using checkboxes but struggling to implement the desired functionality. What I want is to allow only one checkbox selection out of 4 options ...

Encountered an error while attempting to load module script

Upon launching an Angular application on Heroku, a situation arises where accessing the URL displays a blank page and the console reveals MIME type errors. The error message reads: "Failed to load module script: The server responded with a non-JavaScrip ...

Storing data using angular-file-upload

In my application, I am utilizing the "angular-file-upload" library to save a file. Here is the code snippet that I am using: $scope.submitForm = function(valid, commit, file) { file.upload = Upload.upload({ url: '/tmp', data ...

Prevent the print dialog window from appearing when a page loads in Selenium for Firefox and Chrome

Is there a way to prevent the print window from automatically popping up when a page loads using Selenium? So far, I have tried using the Robot class to press the escape key, but it only works 80% of the time. I have also experimented with Firefox prefere ...