Establish a background image for a particular item within a list

Employing Ionic 2 with Typescript.

I am seeking a way to empower users to choose the background color for each item in my list.

ISSUE: How can I retrieve the reference to the i-th element? Whenever I select an item, it only changes the background of the first element in the list.

Left Image: ERROR - Right Image: DESIRED OUTCOME https://i.sstatic.net/girkz.jpg

Let's delve into the code:

NOTE.HTML

<ion-content class='lista'>
    <ion-list reorder="true" (ionItemReorder)="reorderItems($event)">
        <ion-item-sliding *ngFor="let alimento of listaSpesa">       
            <ion-item text-wrap class="popover-page" #popoverList> // FOR BACKGROUND
                <ion-grid>
                    <ion-row center>
                        <ion-col width-10 (click)="setPopOver($event, alimento)">
                            <ion-buttons>
                                <button dark clear disabled full>
                                    <ion-icon name="more"></ion-icon>
                                </button>
                            </ion-buttons>
                        </ion-col> 
                        <ion-col width-10>
                            <img src="{{alimento.userImg}}" class="imgAlimenti" />
                        </ion-col>
                        <ion-col width-80>
                            <ion-row>{{alimento.id}} - {{alimento.id_lista}} </ion-row>
                            <ion-row><p>{{alimento.descrizione}} - </p></ion-row>
                        </ion-col>
                    </ion-row>
                </ion-grid>    
            </ion-item>               
        </ion-item-sliding>
    </ion-list>
</ion-content>

.CSS

.popover-page {    
    ion-row,
    ion-col {
        padding: 0;
    }    
    .row-dots {
        text-align: center;

        .dot {
            height: 3rem;
            width: 3rem;
            border-radius: 50%;
            margin: 10px auto;
            position: relative;
            border: 1px solid white;
        }
    }

    .dot-white { background-color: rgb(255,255,255); }
    .dot-tan { background-color: rgb(249,241,228); }
    .dot-grey { background-color: rgb(76,75,80); }
    .dot-black { background-color: rgb(0,0,0); }
    .dot.selected {
        border-width: 2px;
        border-color: #327eff;
    }
}

.TS

@Component({
  templateUrl: './build/pages/notes/notes.html'
})

...

In essence, my current code always points to the initial element in the list.

PS: I ask for forgiveness in case of any grammatical errors in my English.

Answer №1

Issue Resolved (slightly different from the initial problem):

.HTML Insert this code into your container.

<ion-item text-wrap [ngStyle]="{'background-color': alimento.colore}" class="popover-page" #popoverList>
</ion-item>  

.TS

@Component({
  templateUrl: './build/pages/notes/notes.html',
})
export class NotesPage {

  constructor(private popoverCtrl: PopoverController) {}

    setPopOver(myEvent, alimento: Alimento) {
        let index = this.listaSpesa.indexOf(alimento);
        if (index > -1) {
            let popover = this.popoverCtrl.create(PopoverDetailsPicker, {coloreBG: this.listaSpesa[index].colore});
            popover.onDidDismiss(val => {
                if (val !== null) {
                    switch (val) {
                        case 'white':
                            this.listaSpesa[index].colore = '#ffffff';
                            break;
                        case 'lightBlue':
                             this.listaSpesa[index].colore = '#ccf5ff';
                            break;
                        case 'lightRed':
                            this.listaSpesa[index].colore = '#ffd1b3';
                            break;
                        case 'lightGreen':
                            this.listaSpesa[index].colore = '#ccffcc';
                            break;
                        case 'lightYellow':
                            this.listaSpesa[index].colore = '#ffffb3'; 
                            break;                                                        
                        default:
                            Toast.show('Incorrect choice.', '1000', 'center').subscribe(toast => {});  
                    }
                }
            });
            popover.present({
               ev: myEvent
            });
        }
  }
}

@Component({  // POPUP DEFINITION
    template: `
    <ion-list radio-group class="popover-page">
        <ion-row class="row-dots">
            <ion-col>
                <button (click)="switch('white')" category="dot" class="dot-white" [class.selected]="background == 'white'"></button>
            </ion-col>
            <ion-col>
                <button (click)="switch('lightBlue')" category="dot" class="dot-lightBlue" [class.selected]="background == 'lightBlue'"></button>
            </ion-col>
            <ion-col>
                <button (click)="switch('lightRed')" category="dot" class="dot-lightRed" [class.selected]="background == 'lightRed'"></button>
            </ion-col>
            <ion-col>
                <button (click)="switch('lightGreen')" category="dot" class="dot-lightGreen" [class.selected]="background == 'lightGreen'"></button>
            </ion-col>
            <ion-col>
                <button (click)="switch('lightYellow')" category="dot" class="dot-lightYellow" [class="selected"]="background == 'lightYellow'"></button>
            </ion-col>
        </ion-row>    
    </ion-list>
    `
})
class PopoverDetailsPicker {

  background: string;
  contentEle: any;
  colors = {
    'white': {
      'bg': '#ffffff'
    },
    'lightBlue': {
      'bg': '#ccf5ff'
    },
    'lightRed': {
      'bg': '#ffd1b3'
    },
    'lightGreen': {
      'bg': '#ccffcc'
    },
    'lightYellow': {
      'bg': '#ffffb3'
    },
  };

constructor(private viewCtrl: ViewController, private navParams: NavParams) {}

    ngOnInit() {
        if (this.navParams.data) {
            this.contentEle = this.navParams.data.coloreBG;
            this.background = this.getColorName(this.contentEle);
        }
    }

    getColorName(background) {
        let colorName = 'white';
        if (!background) return 'white';

        for (var key in this.colors) {
            if (this.colors[key].bg === background) {
                colorName = key;
            }
        }
        return colorName;
    }

    switch(choice: any) {
        if (choice !== null) { 
            this.viewCtrl.dismiss(choice); // returns the user's selected choice
        }
    }
}

Click the link below for a preview: https://i.sstatic.net/1S4Ts.png

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

Modifying Bootstrap Grid Layouts

I need to reorganize the columns for better responsiveness as the current order is not ideal. Below is the code snippet: <div class="tab-content" id="pills-tabContent"> <div class="tab-pane fade show active" id="pills-home" role="tabpanel" ari ...

Display the list box against the masked background

I currently have a masked background and a drop-down hidden behind it. Here is how it appears: https://i.sstatic.net/QTLN5.png However, I want it to look like this: https://i.sstatic.net/ZAreM.png This is the HTML code being used: <div id="sugges ...

Disguising the Navigation Bar when choosing from various databases

I am currently facing the following issue: <div class="container"> <h3 class="d-flex justify-content-center">Database</h3> <div class="row"> <div class="col-xs-12"> < ...

Is it possible to nullify an object and utilize nullish coalescing for handling potentially undefined constants?

In my development work with React, I often utilize a props object structured like this: const props: { id: number, name?: string} = { id: 1 }; // 'name' property not defined const { id, name } = props; // the 'name' constant is now fore ...

What is the optimal event to trigger a function when there is any modification in a text area using Javascript?

I need a function to trigger every time there is any modification in my textarea, such as characters being typed, deleted, cut, pasted, etc. Currently, I am using: onkeyup || onmousemove = function(); It appears that only onmousemove is being triggered. ...

Guide to adding annotations to a PDF document using Angular 2

As a novice in the field of Angular development, I am seeking guidance. Currently, I have an application that displays PDF files. My goal is to be able to annotate and make changes on these PDF files by adding drawings such as circles, lines, or text. Ho ...

Leveraging JavaScript to extract data from a dropdown menu and apply it to a different section

I am working on a project that involves an HTML section where a user can choose a billing term from a drop-down list. I am in the process of writing JavaScript code to capture the selected option value and use it in another part of the webpage. Here is a ...

sidebar that appears upon the initial page load

I'm currently working on implementing a sidebar navigation panel for my website using JavaScript, HTML, and CSS. However, I am facing an issue where the sidebar automatically opens when the page is first loaded, even before clicking on the icon to ope ...

What is the process for implementing custom color props with Material-UI v5 in a React TypeScript project?

Looking to enhance the MUI Button component by adding custom color props values? I tried following a guide at , but encountered errors when trying to implement it in a custom component. The custom properties created in createPalette.d.ts did not work as ex ...

Utilizing TypeScript to Define Object Properties with String Keys and Values within Parentheses

I am in the process of developing a telegram bot I have the need to save all my messages as constants My message schema is structured as follows: type MessagesSchema = { [K in keyof typeof MessagesEnum]: string } Here is an example implementatio ...

creating a live updating dropdown menu using Node.js and MySQL

Upon a user clicking and selecting a client, I would like to dynamically update the region dropdown menu with options that are related to that specific client from the databaseenter code here This is my client table: Here is the Region table, where clien ...

Sending various data from dialog box in Angular 8

I have implemented a Material Design dialog using Angular. The initial example had only one field connected to a single parameter in the parent view. I am now trying to create a more complex dialog that collects multiple parameters and sends them back to t ...

A guide to determining the date based on the selected item in a dropdown menu in Ionic2

As a newbie in Ionic 2, I am looking to calculate dates based on the dropdown item selected in my hybrid Ionic application. The page consists of two dropdowns: First Dropdown list https://i.sstatic.net/hGaLM.png Second Dropdown https://i.sstatic.ne ...

Include the document when the query results in zero documents

Struggling to figure out how to add a document to a collection if a query returns no results. The current query lacks operators for checking the length or size of the result. How can this be achieved? The query in question: this.monthCollection = this.af ...

When a div tag containing PHP is empty, it should either be hidden or show specific text based on your requirements

Among the plethora of unanswered queries regarding hiding empty divs, I find myself unable to make any of the suggested solutions work. Hence, I am putting forth my own question. On my webpage, there is a specific section dedicated to showcasing various it ...

Enhancing Angular Material forms with custom background colors

I'm new to Angular and Angular material, still learning the ropes. I have been trying to create a form and needed to change the background color to Red. However, when I attempted to do so, the red color ended up covering the entire form instead of ju ...

Eliminating the boundaries of Bootstrap accordion

I'm currently working on creating Bootstrap accordion menus and I'm attempting to remove the border that appears when it's collapsed and expanded. Below is the code I've been working on: <div class="accordion"> <div ...

Tips for Creating Sand Text Effects in CSS (Using Text-Shadow)

I am attempting to create a CSS effect that resembles text written in the sand. Here is an example of what I am trying to achieve: As a newcomer to CSS, I would appreciate any guidance on how to make this effect possible. I have tried using the following ...

Issues have arisen in IE8 with the background gradient on hover elements in the menu, while it functions properly in all other web browsers

Welcome to the website: I've recently taken on a project involving the gradiated menu on this site. The menu works flawlessly in Firefox, Chrome, and Safari - the hover effect changes the background color to a light gradiated green. However, when it ...

Tips for addressing the ESLint issue stating that the package should be included in dependencies instead of devDependencies

Struggling to properly lint my React+Typescript project with ESLint. In one of my components, I'm utilizing the useParams hook from react-router. import { useParams } from 'react-router'; However, ESLint is throwing an error on that line: E ...