How to select just one item on Ionic?


#1

I’ve just started using Ionic 2 and I don’t know how to select just one item. I’ve got a list of adresses, when I select one, the whole list is selected.


HTML


<ion-list>
                <ion-item (click)="selectAddress(adress)" *ngFor="let address of addresses">
                    <ion-avatar item-left *ngIf="item == false">
                        <ion-icon name="md-add"></ion-icon>
                    </ion-avatar>
                    <ion-avatar aria-label="Checkbox 2" ng-true-value="'yup'" item-left *ngIf="item == true">
                        <ion-icon name="md-checkmark"></ion-icon>
                    </ion-avatar>
                    <h2>{{adress.city}}</h2>
                </ion-item>
                <ion-item color-text = "danger" (click)="addAdress()" *ngIf="address.length == 0">
                    <ion-avatar item-left>
                        <ion-icon name="md-home"></ion-icon>
                    </ion-avatar>
                    <h2 class="danger1">There are no addresses</h2><p></p>
                    <h3 class="danger2">Click to register</h3>
                </ion-item>
</ion-list>```



TypeScript

item: boolean = false;
selectAddress(address: any) {
    this.address= address;
    if (this.item == true) {
      this.item = false;
      this.address = null;
    } else {
      this.item = true;
    }
     }

The method addAddress I just send the selected address ‘this.address= address;’ to Java. I need to select just one address. On this way I’ll select just one, for Java, but the icon will be the same for all. How can I do that?


#2

You seem to have only one item (how I hate variable names like this) that is shared amongst all addresses. Is this what you intend?


#3

Kindda, I don’t know how to explain this correctly (english is not my first language). When I click on one item (I have a lot of addresses and I select one). This one which was selected is going to Java (Post Method). But, cause of my resolution of this problem when I select the address, the icon will change for all the address, this is basically the problem of mine.


#4

If I am understanding you correctly, I would do this:

export interface Address {
  city: string;
  // whatever else goes in here
}

addresses: Address[] = [];
chosenAddress: Address;

<ion-list>
<ion-item *ngFor="let address of addresses" (click)="chosenAddress = address">
  <ion-avatar>
    <ion-icon [name]="address === chosenAddress ? 'md-checkmark' : 'md-add'"></ion-icon>
  <ion-avatar>
  <h2>{{address.city}}</h2>
</ion-item>

<ion-item *ngIf="addresses.length === 0" (click)="addAddress()">
  no addresses case
</ion-item>

chosenAddress would be the one you want to send to the backend.


#5

I’ll try this one, thank you for replying.