I am trying to create an image modal where if you click on an image, it creates an enlarged preview. I have three images from services and I display all three using *ngFor. However, when one image is clicked, all three get enlarged. I know I can use $(this) so the click function knows which image url to enlarge but I'm not sure exactly how to implement. Any help will be appreciated. If I need to install jquery to get this to work or import it, please let me know. Thanks!
component
import { Component, OnInit } from '@angular/core';
import { RandomdogpicsService } from './randomdogpics.service';
@Component({
selector: 'app-gallery',
templateUrl: './gallery.component.html',
styleUrls: ['./gallery.component.css']
})
export class GalleryComponent implements OnInit {
picData: any;
title:string = 'Random dog pics';
showModal: boolean = false;
show()
{
this.showModal = true; // Show-Hide Modal Check
}
//Bootstrap Modal Close event
hide()
{
this.showModal = false;
}
constructor(private threeRandomData: RandomdogpicsService){}
ngOnInit()
{
this.threeRandomData.getThreeRandom().subscribe((result) => {
this.picData = result
})
}
}
html
<h1>{{title}}</h1>
<ul *ngFor="let randomURL of picData.message">
<li >
<a href="#" (click) = "show()">
<img id="imageresource" src="{{randomURL}}" style="width: 125px; height: 125px;">
</a>
<!--Creates the bootstrap modal where the image will appear -->
</li>
</ul>
<div [style.display]="showModal ? 'block' : 'none'" class="modal" id="imagemodal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myModalLabel">Image preview</h4>
</div>
<div class="modal-body">
<!-- need to pass {{randomURL}} here -->
<img src="" id="imagepreview" style="width: 425px; height: 425px;" >
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal" (click) = "hide()">Close</button>
</div>
</div>
</div>
</div>
Update: Following the suggestion, I moved the modal div outside of the for loop. I tinkered with my CSS to block the screen so I can keep it inside the for loop as well and the user won't notice that all images are displayed. However, the image that shows up is always the last image of the for loop. So either I 1) put the div modal inside the for loop but figure out how to prevent it from choosing the last url in the for loop or 2) I put the div modal outside the for loop but pass {{randomULR}} to img src.
you should (almost) never use jQuery with Angular. Angular can basically do everything that jQuery does.
in your case you can pass the clicked image as a parameter function:
(click)="show(randomURL)"
so you know wicht url was clicked.
You have to place the modal Outside of the ngFor, otherwise you will have 3 modals.
A tip I can give you, is to use Angular Material Dialog or CDK Dialog to show a modal instead of your own.