Home > OS >  Ionic4 Angular: dynamically creating ion-select with *ngFor results in linking all ion-select-opti
Ionic4 Angular: dynamically creating ion-select with *ngFor results in linking all ion-select-opti

Time:09-23

I need to create a list of ion-select based on an array inside an object called myObject.array.

  • When I create the list using mypage.page.ts and mypage.page.html code listed below. All my ion-select-options get linked together - so when I change one ion-select to Y all ion-select changes to Y etc.
  • I can see in my console log that ionChange is fired up only once - ale inside it I can also see correct data (that only one item inside a myObject.array is changed).
  • The problem is that UI doesn't correspond with the data inside the mypage.page.ts

Picture below shows UI after I change only one ion-select and console log (you can see that multiple ion-select changed and the console log data doesn't correspond with the UI):

enter image description here

How can I create ion-selects dynamically from an array and don't link them with eachother?

Edit:

  • The errors in the console are related to cookies (with this error message : Indicate whether to send a cookie in a cross-site request by specifying its SameSite attribute).
  • The errors are unrelated to my code because whether I add the page or delete it they are still there.

My code:

<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>

And this 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);
  }

CodePudding user response:

trackBy is something made to improve change detection performance.

Just for the record here's how one make it "trackBy" index:

Template change

<ion-item *ngFor="let output of myObject.array; let i=index; trackBy:indexTracker;">

Controller change

indexTracker(index: number, value: any) {
    return index;
}
  • Related