1

As part of my Angular 2 app I generate a list 'views', containing the paths to a bunch of images. I use ng-repeat to cycle through the images and display them 1-by-1 in a ui-view. I'd like to add an event listener to this so that when an image clicked, the image src is added to an array. Clicking the image again would remove it from the array. I've taken a look at involving a jquery plugin Image Picker, but that quickly becomes too messy.

Isn't there a way to do this from Angular 2 natively?

views.html

<body>
  {{views.length}} views found.
  <br>
  <div style="display:inline-block" ng-repeat="x in views">
    <section ui-view>
      <img src={{x}} alt={{x.substring(20,60)}} style="width:192px;height:192px;">
    </section>
</body>

1 Answer 1

1

In your template you could leverage the (click) event like this:

<img src={{x}} alt={{x.substring(20,60)}} (click)="toggleImageInList(x)" style="width:192px;height:192px;">

And in your component you have a method to actually add and remove the image source somewhere in an array:

toggleImageInList(image) {
    if (this._images.indexOf(image) >= 0) {
        this._images = this._images.filter((img) => img !== image);
    }
    else {
        this._images.push(image);
    }
}

Plunker for example usage :)

Sign up to request clarification or add additional context in comments.

5 Comments

Mm interesting and clean. Is there a way for me to check whether the array is being filled or not?
What do you mean exactly? If you fall into the if (this._images.find(image) >= 0) clause, then it removes the image from the array (by filtering it out). Otherwise it falls into the else clause and pushes the image into the array.
Intuitively I agree it should work, however when I try it the method doesn't seem to fire. Hence, a suggestion as to an easy way (extra line?) I could add to verify that it works?
Ah, I made a tiny mistake. Use indexOf instead of find - mixed that up :) - I'll edit my answer!!
If this worked out for you, could you please accept it as the answer?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.