user8770372
user8770372

Reputation:

Angular hide and show images depending on selected passed parameter

I have a dropdown:

<ul class="dropdown-menu">
    <li><a href="#" (click)="showSelectedImage(1)">Option 1</a></li>
    <li><a href="#" (click)="showSelectedImage(2)">Option 2</a></li>
    <li><a href="#" (click)="showSelectedImage(3)">Option 3</a></li>
</ul>

and I have 3 images:

<img class="hidden" src="image1.png" alt />
<img class="hidden" src="image2.png" alt />
<img class="hidden" src="image3.png" alt />

In app.component.ts I have this method:

showSelectedImage(image) {
    // ... 
}

What I need to do is when an image is selected from the dropdown menu, I need that image to be shown and the others to be hidden.

Upvotes: 0

Views: 486

Answers (3)

Christian
Christian

Reputation: 51

If you wanted to separate the image urls and descriptions, you could put them in a list within your component code and then display them in the template using an ngFor. That way they can be called whatever (rather than having to be image1, image2, image3 etc.) and could be easily changed in the future without having to edit your template each time (e.g. from a dynamic list).

E.g.: Template:

<ul class="dropdown-menu">
    <li *ngFor='let image of images'><a href="#" (click)="showSelectedImage(image)">{{image.description}}</a></li>
</ul>

<img *ngIf='selectedImage' src="{{selectedImage.src}}" alt />

app.component.ts:

selectedImage;
images: list = [
    {src: 'image1.jpg', description: 'Image 1'},
    {src: 'image2.jpg', description: 'Image 2'},
    {src: 'someotherimage.jpg', description: 'Some other Image'}
];

showSelectedImage(image) {
    this.selectedImage = image;
}

Example Plunker

Upvotes: 1

Jeremy Thille
Jeremy Thille

Reputation: 26370

Just generate one image with the corresponding source :

<ul class="dropdown-menu">
    <li *ngFor="let i of [1,2,3,4,5,6]">
        <a href="#" (click)="showSelectedImage(i)">Option {{i}}</a>
    </li>
</ul>

<img src="image{{imageId}}.png" *ngIf="imageId" />

Component :

imageId:Number;

showSelectedImage(id){
    this.imageId = id
}

Upvotes: 4

Pac0
Pac0

Reputation: 23174

<ul class="dropdown-menu">
    <li><a href="#" (click)="showSelectedImage(1)">Option 1</a></li>
    <li><a href="#" (click)="showSelectedImage(2)">Option 2</a></li>
    <li><a href="#" (click)="showSelectedImage(3)">Option 3</a></li>
</ul>


<img class="hidden" src="image1.png" alt *ngIf="selectedImage==1"/>
<img class="hidden" src="image2.png" alt *ngIf="selectedImage==2"/>
<img class="hidden" src="image3.png" alt *ngIf="selectedImage==3"/>

app.component.ts

private selectedImage: number;

showSelectedImage(imageNumber: number) {
    this.selectedImage = imageNumber; }

Upvotes: 0

Related Questions