How to re-factor this NativeScript simple image css swapper

Viewed 50

I have a page that displays 3 images, and the user is expected to tap on one, then tap the Next button to continue.

My Page

So basically, I am simply adding some CSS to the image when it is tapped.

BUT... my code is ugly, and doesn't keep track of whether they ALREADY have one selected.

 onPlanTap: function (args) {
        const planImage = args.object;
        const planImageSrc = planImage.src;
        const planId = plan.id;

        this.set("nextButtonOn", true);

        var n = planImageSrc.search("off");

        // Found, it is off - turn on
        if (n > 0) {
            var newOnSrc = planId + "-off.png";
            planImage.src = newOnSrc;
            this.set("currentPlan",planId);
            FancyAlertService.showFancySuccess("Plan Secected!", "You have chosen the FREE plan.", "Ok");
        }
        else {
            // It's already on, turn off
            var newOnSrc = planId + "-on.png";
            planImage.src = newOnSrc;
            this.set("currentPlan","");
        }

    }

[ oh, the css I am adding, simply adds a thick white border to the image ]

I can't figure out how to only have one selected.

Is there some sort of "toggle" feature in NS I am missing, or would I have to write the logic myself? If that's the case, can anyone give me a nudge with some code?

1 Answers

Wrap your images inside some custom object.

class MyImage {

image;
isSelected:boolean;
}

Add data binding:

<ListView [items]="myDataItems" class="list-group">
    <ng-template let-item="item" let-i="index">
        <Image (tap)="selectImage(item)" class="item.isSelected ? styleA : styleB"></Image>
    </ng-template>
</ListView>

And in your component file:

class MyComponent {
    myDataItems: Array<MyImage>

    selectImage(item: MyImage) {
        //deselect all Items
        //select this item
    }
}
Related