Search code examples
angularmobileionic-frameworkionic2hybrid

Change multiple item images when pressed


New to ionic 2, Looking for implementing multi select check box feature on top of ion-list >> ion-item >> avatar image. Meaning, in a contact list , user should be able to press and hold and select multiple contacts from that list. any css built-in or custom approach to change avatar image to avatar image with check box and select?

(Please let me know if this is not clear, thanks)


Solution

  • Best way is probably not having a checkbox (or faking it with css) and then in you component create a selectedList which will keep track of which avatars are clicked on (assuming they have f.e. an id as identifier).

    Html:

    <ion-header>
      <ion-navbar primary>
        <ion-title>
          Ionic 2
        </ion-title>
      </ion-navbar>
    </ion-header>
    
    <ion-content class="has-header">
      <ion-list>
       <ion-item *ngFor="let contact of contactList">
          <ion-avatar (click)="clickedAvatar(contact.id)"
             [class]="isInArray(contact.id) ? 'selected' : 'not-selected'"
                item-left>
                <img src="https://pickaface.net/assets/images/slides/slide2.png"/> <!-- get image from contact object --> 
            </ion-avatar>
            <h2>{{contact.name}}</h2> <!-- etc -->
       </ion-item>
    </ion-list> 
    </ion-content>
    

    ts:

    import { Component } from '@angular/core';
    
    
    @Component({
      templateUrl:"page1.html"
    })
    export class Page1{
      contactList: any[];
    
      selectedContacts: any[];
    
        constructor(){
           this.selectedContacts = [];
           this.contactList = [{
        id: 1,
        name: "Steve"
      },
      {
        id: 2,
        name: "Mark"
      },
      {
        id: 3,
        name: "Lauren"
      }];
        }
    
        clickedAvatar(id: number){
    
          console.log(this.selectedContacts);
           if(this.isInArray(id)){
             let index = this.selectedContacts.indexOf(id);
    
             this.selectedContacts.splice(index,1);
           }else{
              this.selectedContacts.push(id);
              console.log(this.selectedContacts.indexOf(id));
           }
        }
    
        isInArray(id: number): boolean{
          let check: boolean = false;
          for(let contactId of this.selectedContacts){
             if(contactId == id){ 
               check = true;
             }
          }
          return check;
        }
    }
    

    css

    .selected img{
        opacity: 0.4;
    }
    

    The (click) event will execute on a tap and on a longer press. If you want to use only tap or the actual press and hold you should change (click) to (press) or (tap).

    (wrote this from memory so might be incorrect classnames or a typo somewhere :) ). (I'll try to create a plunkr)