Tips for picking out a particular item from a list of child elements

When I select the first parent's children array, it ends up selecting every other parent's children as well. This is due to index 0 remaining the same for all of them. How can I specify and highlight a specific child?

Link: Check out the stackblitz playground

I've attempted comparing the indices of parents and children, but I still can't pinpoint and highlight a specific child within the array.

home.html

<style>
  .highlight {
    background-color:#777;
  }
</style>

<ion-item *ngFor="let date of testList"> 
    {{date.date}} 
    <ion-item *ngFor="let item of date.item; let i = index" [class.highlight]="i === selectedOne" (tap)="onSelected(i)">
           {{item.name}}
    </ion-item>
  </ion-item>

home.ts

  public testList: any[] = [
    {
      date: 'test1',
      item: [{
        name:'tony',
        id:23
      },
       {
         name:'shawn',
         id:12
       },
       {
         name:'rancho',
         id:33
       }
      ]
    },
{
      date: 'test2',
      item: [{
        name:'Monty',
        id:345
      },
       {
         name:'Bob',
         id:321
       },
       {
         name:'Dexter',
         id:324
       }
      ]
    },
    {
      date: 'test3',
      item: [{
        name:'Trillo',
        id:234
      },
       {
         name:'Stenly',
         id:12
       },
       {
         name:'Destro',
         id:123
       }
      ]
    }
  ]

  public selectedOne: boolean 
  onSelected(index) {
     if (this.selectedOne !== index) {
          this.selectedOne = index;
        } else {
          this.selectedOne = null;
        }
  }

I am aiming to identify and highlight a specific child item.https://i.sstatic.net/1FRe2.png

Answer №1

To enhance the functionality, I suggest implementing a selected attribute for each item displayed in the list. This can be achieved by adding the following code snippet within the ngOnInit() method.

 constructor(public navCtrl: NavController) {
     this.testList.forEach(data => data.item.forEach(each => 
        {
          each.selected = false;
        })
     )
  }

This approach allows you to keep track of whether an object has been selected or not. To reflect these changes in your HTML, modify the code as shown below. When clicked, pass both the item and its parent instead of just the index. The [class.highlight] directive will check if selected is set to true or false.

<ion-content padding>
  <ion-item *ngFor="let date of testList"> 
    {{date.date}} 
    <ion-item *ngFor="let item of date.item; let i= index" 
        [class.highlight]="item.selected" (tap)="onSelected(item, date)">
           {{item.name}}
    </ion-item>
  </ion-item>
</ion-content>

Furthermore, refine the function triggered on click event to toggle the value of selected, switching between true and false.

Edit

Create a separate clear function to reset all selected states, ensuring uniformity across all items.


onSelected(item, parent)
{ 
    this.testList.forEach(data => data.item.forEach(each =>
        { each.selected = false; }));

    item.selected ? item.selected = false : item.selected = true;
}

Answer №2

VERIFY VIEW WORKING STACKBLITZ

Your home.html should resemble the following:~

<ion-header>
    <ion-navbar>
        <ion-title>Home</ion-title>
    </ion-navbar>
</ion-header>


<style>
    .highlight {
        background-color: #777;
    }
</style>

<ion-content padding>
    <ion-item *ngFor="let date of testList">
        {{date.date}}
        <ion-item *ngFor="let item of date.item; let i= index" [class.highlight]="item.id == selectedOne" (tap)="onSelected(item)">
            {{item.name}}
        </ion-item>
    </ion-item>
</ion-content>

Ensure your home.ts contains the onSelected method as shown below:~

  onSelected(item) {
    this.selectedOne = item.id;
  }

Answer №3

Modify the selectedOne variable to an Object data type

public selectedOne = {id: 12, name: 'Stenly'};

Also, make sure to update the condition in the loop

[class.highlight]="(item.id == selectedOne.id && item.name == selectedOne.name)"

<ion-item *ngFor="let item of date.item; let i= index" [class.highlight]="(item.id == selectedOne.id && item.name == selectedOne.name)" (tap)="onSelected(i)">
           {{item.name}}
    </ion-item>

https://stackblitz.com/edit/ionic-select-one

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

Is it possible to sketch basic 2D shapes onto 3D models?

Is the technique called projective texture mapping? Are there any existing library methods that can be used to project basic 2D shapes, such as lines, onto a texture? I found an example in threejs that seems similar to what I'm looking for. I attempt ...

JavaScript - Declaring canvas as a global object

Presently, I am experimenting with HTML5 and using JavaScript to create a basic 2D Tile map. Progress is going smoothly; however, I have come across an issue where I am unable to contain everything within one large function. I am attempting to make the ca ...

When I engage with the input field, it ceases to be in focus

Here is the code I've been working on: https://github.com/Michael-Liendo/url-shortener/blob/main/src/pages/index.js If you want to see the issue for yourself, check it out at: ...

JQuery not refreshing data values

function addToRewardDatabase() { var rewardValue = "98"; $.post("db/mkreward.php", { proid: getURLParameter("id") }, function(data) { rewardValue = "99"; alert(rewardValue); }); alert(rewardValue); return ...

"Enhance your audio experience across all browsers with the revolutionary

I am looking for a way to play an mp3 file endlessly when the user opens my website. I need a lightweight crossbrowser solution that works in all browsers, including IE. Any suggestions? ...

What criteria should I consider when selecting a make for the createTheme components?

After reviewing the documentation for the createTheme component, I noticed examples with MuiButtonBase, MuiButton, and MuiSlider. However, when it comes to adding a button, it's simply called Button, not MuiButton. So, does this mean I just need to p ...

Turn off scroll bar to create a seamless browsing experience on your website

As I work on creating the frontend for a single-page website with seamless scrolling between divs, I'm looking to eliminate mouse scrolling altogether. I understand that using overflow:hidden; can hide scroll bars, but my goal is to make the page scr ...

Is there a way to simultaneously click on a link on one page and alter the position of a particular class on another page?

I have been working on designing two pages for a website. I am looking to use JavaScript to ensure that when a link on page 1 is clicked and the user transitions to page 2, the second tab button (btn) will have an id of "default" and receive the activate c ...

What is the best way to choose a specific JSON element?

Seeking information from an API, my goal is to extract specific data using JavaScript selectors. I am specifically interested in two objects from the JSON below: [ { "symbol": { "tickerSymbol": "@CH20", "vendor": "DTN", "marketName ...

The function url_for is failing to interpret the variables I am passing to

My goal is to allow users to upload images that are then displayed to all users. The variable "Data" holds the file name (e.g., "files/dog.png"). However, when I try to set the newImg.src value as "{{url_for('static', filename = data )}}", it onl ...

Localhost is unable to process AngularJS routes containing a dot in the URL

When using the route provider and setting this specific route: .when('/:name/:id', { It successfully navigates to my desired path and executes the code when I enter: https://localhost.myapp.com:9000/Paul/123 However, it fails to work with this ...

Is the renderer.setSize in Three.js calculated as a percentage of the screen size?

Is it possible to calculate the renderer.setSize based on a percentage of the screen? For instance, could I set my frame to be 80% of the device width and 80% of the device height? ...

Ember.js encountering an "Access-Control-Allow-Origin" error with Ajax

Seeking opinions on how to resolve the Access-Control-Allow-Origin issue in this simple Ajax code snippet. Attempts to define the Ember "Access-Control-Allow-Origin": "* " have been unsuccessful. Has anyone with a similar problem found a solution? The URL ...

Preventing AJAX/hash functionality for specific links exclusively within jQuery Mobile

I've come across some outdated solutions for this issue, but it seems they are no longer applicable to jQuery Mobile. My goal is to disable the AJAX/hashbang behavior for specific links only. I know that I can disable it globally like this: /** * ...

Ensure that the Observable is properly declared for the item list

.html // based on the error message, the issue seems to be in the HTML code <ion-card *ngFor="let invitedEvent of invitedEvents"> <ion-card-content> <img [src]="eventPhotoUrl$[invitedEvent.id] | async"> </ion ...

Why do I keep being told that the property doesn't exist?

I have the following code in one file: function test<T extends {}>(arg:T):any { return arg.name } In another file, I have this code: interface IItem { name: string } console.log(test<IItem>({name:'3'})) When I try to access ...

Applying binary information to an image

Let's say I have an <img/>. The img is initially set with src='http://somelocation/getmypic'. Later on, there might be a need to change the content of the image based on some ajax call that returns binary data. However, this decision c ...

Angular 5 Web-Based EPUB Reader

Just getting started with Angular 5 and I'm looking to display an epub file on a page without resorting to iframes. Any suggestions on how to achieve this? ...

Express routes are malfunctioning

I have a situation with two different routes: /emails and /eamils/:id: function createRouter() { let router = express.Router(); router.route('/emails/:id').get((req, res) => { console.log('Route for get /emails/id'); }); ...

Dealing with special characters in Mustache.js: handling the forward slash

I have a JSON file that contains information about a product. Here is an example of the data: { "products": [ { "title": "United Colors of Benetton Men's Shirt", "description": "Cool, breezy and charming – this s ...