Open image gallery in lightbox in Angular Apps

In this article, we discuss how to open image gallery in our angular application. First, we need to install “Ngx-Lightbox” module in our application.


npm install --save ngx-lightbox

After installing module we need to import their CSS in our angular.json file


.....
{
  "styles": [
    "./node_modules/ngx-lightbox/lightbox.css",
    ...
  ],
}
.....

After adding CSS now we need to import module in our “app.module.ts” file.


import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';

import { AppComponent } from './app.component';
//lightbox
import { LightboxModule } from 'ngx-lightbox';

@NgModule({
  imports:      [ BrowserModule, FormsModule, LightboxModule  ],
  declarations: [ AppComponent, HelloComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }



We need to create albums for display images, each albums item contains maily 3 proertyies.
1) src: Required field – it contains main image path when click on the thumbnail or text.
2) caption: Optional field – Name of the image display below the image.
3) thumb: Optional field – small image of the main.


<div style="padding-top:50px"></div>

<div class="container">

<h3>Imag Gallery</h3>
<!-- Content here -->
<div class="row">

<div class="col-sm" *ngFor="let image of album; let i=index">
<img [src]="image.thumb" (click)="open(i)" />
</div>

</div>

</div>


import { Component } from '@angular/core';
import { Lightbox } from 'ngx-lightbox';

@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular';
album:any = [];
constructor(private _lightbox: Lightbox) {

this.album.push({'src':'https://via.placeholder.com/500','caption':'Imag1','thumb':'https://via.placeholder.com/150'});

this.album.push({'src':'https://via.placeholder.com/500','caption':'Imag1','thumb':'https://via.placeholder.com/150'});

this.album.push({'src':'https://via.placeholder.com/500','caption':'Imag1','thumb':'https://via.placeholder.com/150'});

}

open(index: number): void {

this._lightbox.open(this.album, index);
}

close(): void {

this._lightbox.close();
}
}



Below is the running embedded code for open image gallery.

Spread the love
  •  
  •  
  •  
  •  
  • 1
  • 1
  •  
  •