Ygor Fraga Ygor Fraga -3 years ago 70
TypeScript Question

How to select just one item on Ionic?

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?

Answer Source

You need to accommodate for the array that is happening. You have only one item and yet an array of addresses. What I usually do is stick selected on the object of the ngFor.

public selectAddress(address: any): void {
    this.address = address;
    address.selected = !address.selected || false;
} 

Then test it like this:

<ion-avatar item-left *ngIf="address.selected === false">
     <ion-icon name="md-add"></ion-icon>
</ion-avatar>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download