Building an Image Gallery with Angular
Creating a good looking Image Gallery with Angular is an awesome project to work on because it covers some basic understanding of what front end development is and what front end developers do.
So in this project, we will be looking out on how we can use Unsplash api to build a beautify Image Gallery and also how we can lazyload an image.
Below is what we need to know before we proceed:
- Little knowledge of the framework(Angular)
- Angular Cli installed in our system
- A text editor
- Node.js installed in our system
- How to call Api
Prerequisite
Navigate to the folder where you want to create your project file. Open a command window and run the command shown below.
ng new Image-gallery --routing=false --style=scss
The command above creates a new Angular application. The option to create the routing module is set to false and style files extension is set to scss.
We are going to use bootstrap. Run the code to install bootstrap:
cd Image-gallery
npm install bootstrap --save
Add the following import definition in styles.scss file.
@import "~bootstrap/dist/css/bootstrap.css";
What is unsplash api
The Unsplash API is a modern JSON API that surfaces all of the info you’ll need to build any experience for your users. It’s so simple to use that they even run unsplash.com on it!
How to use unsplash api
Before we can access the api below is what we need to do:
Creating a developer account.
When you go to Unsplash API site click on the Developer button on the page and fill in the required details.
Once your account has been registered for the API, go to your apps. Click “New Application”, and fill in the required details. Initially, your application will be in demo mode and will be rate-limited to 50 requests per hour. When ready to move to production mode, follow the ‘Apply for Production’ instructions. If approved, your rate limit will be increased to the full amount.
The Unsplash API uses HTTP verbs appropriate to each action.
Verb | Description |
GET | Retrieving resources. |
POST | Creating resources. |
PUT | Updating resources. |
DELETE | Deleting resources. |
The API is available at https://api.unsplash.com/
. Responses are sent as JSON.
The API has a lot of parameters that we can use, but we’ll only need 4 of them which are :
- Client_id: The client ID generated in your Unsplash API account.
- Photos: Get a single page from the list of all photos.
- Page: Page number to retrieve. (Optional; default: 1)
- Per_page: Number of items per page. (Optional; default: 10)
Creating a Gallery
We will start by generating our gallery component:
ng g c gallery
Open app.gallery.component.html and write the blow code
<div class="container">
<div
class="row justify-content-around align-items-center"
Style="height: 80vh; width:100%"
>
<div class="col-lg-3 col-md-6 col-sm-12 border">
</div>
</div>
</div>
The above code is a simply html tags that we will use to display our image.
Setting up the server
We are going to generate Angular Service and import HttpClientModule in our project so that we can be able to interact with the Unsplash API through http.
Run the code below to generate angular service:
ng generate service api
Open app.module.ts and import HttpClientModule and Service
import { HttpClientModule } from "@angular/common/http";
import { ApiService } from './api.service';
@NgModule({
declarations: [...],
imports: [
HttpClientModule
],
providers: [ApiService],
bootstrap: [...]
})
export class AppModule { }
Open app.api.service.ts and write the code below but first we have to import HttpClientModule.
import { Injectable } from "@angular/core";
import { HttpClient } from "@angular/common/http";
@Injectable({
providedIn: "root"
})
export class ApiService {
constructor(private httpClient: HttpClient) {}
}
Now write the code below:
Key = "Your key";
page = 1;
per_page = 21;
getImage() {
return this.httpClient.get(
`https://api.unsplash.com/photos/?page=${this.page}&per_page=${this.per_page}&client_id=${this.key}`
);
}
In the above code we started by creating a global variable and we assign the value to be our api key which was generated from our app on the Unsplash Api site. We move forward by creating another variable and assign the volume of images we want to display and the page we want to fetch the image from (Page = 1 and per_page = 21). Lastly we created a function called getImage() and called http get() request to fetch data from the serve.
Fetching data
Now, we are going to fetch data from the Unsplash Api. Open app.gallery.component.ts. We will start by import Service so we can be able to access the api end point.
import { Component, OnInit } from '@angular/core';
import { ApiService } from "../api.service";
@Component({
selector: 'app-gallery',
templateUrl: './gallery.component.html',
styleUrls: ['./gallery.component.scss']
})
export class GalleryComponent implements OnInit {
constructor(private apiService: ApiService) { }
ngOnInit() {
}
}
We are going to make a call to our Api service.
ngOnInit() {
this.apiService.getImage().subscribe((resp: any) => {
console.log(resp);
});
}
In the ngOnInit, we subscribe to the Unsplash Api by calling the this.apiService and the getImage() function we created in the ApiService and we console.log the response we get from the serve.
We are going to serve our app and see the response we are getting:
ng serve -o
If our app is serve successfully, open the dev tools and check the response and if the response are in array of 21 items as shown below, then you are on the right track but if not, then you might be missing out somewhere.
Array(21) [ {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, … ]
Displaying Image
Now that we have gotten a success responses we will move further to display our response than going to the console. Open app.gallery.component.ts
export class GalleryComponent implements OnInit {
constructor(private apiService: ApiService) {}
Items;
ngOnInit() {
this.apiService.getImage().subscribe((resp: any) => {
this.Items = resp;
console.log(resp);
});
}
}
We declared a global variable and we assigned it the value gotten from our response and in our app.gallery.component.html we bind Items variable to the div that displays the responses.
<div class="container" *ngIf="Items">
<div
class="row justify-content-around align-items-center"
Style="height: 80vh; width:100%"
>
<div
class="col-lg-3 col-md-6 col-sm-12 border m-3"
style="height:40vh"
*ngFor="let item of Items"
>
<img src="{{ item.urls.small }}" alt="" />
</div>
</div>
</div>
Add Lazyloading to image
Before we move ahead writing, let’s understand what we are trying to do.
Lazy loading images means loading images on websites asynchronously — that is, after the above-the-fold content is fully loaded, or even conditionally, only when they appear in the browser’s viewport. This means that if users don’t scroll all the way down, images placed at the bottom of the page won’t even be loaded.
From the above explanation we are going to load our images asynchronously meaning one after another and only when we scroll to a browser viewport will the next image load.
We may be curios to ask why lazyloading our image? and Why not Load them all at once?
Just from the above explanation, there are several reasons why we should lazy load our images instead of letting them load all at once.
Let’s see the most important of them:
- Improvement in Both Perceived and Real Loading Time for Your Pages: Meaning that, if we observe when our image was loading we will notice that the numbers of images we fetch from the server must download fully before the page becomes 100% usable. But If we lazy load our images the issue will be solved because only those Images at viewpoint we be downloaded in the first instance. This will result in a real reduction of first-page load time as well.
- Reduction of the Work for the Browser: If images are lazy loaded, your browser won’t need to parse nor decode resources until the moment they are requested by scrolling the page.
- Fewer Data Served by the Server: On the same line of the previous points, the server will have to download less data, resulting in cheaper bills for you!
- Reduce the Number of HTTP Requests During the First-Page Load
From the above Explanation we can see why lazyload is important and why we want to lazyload our images. Let move further to implement lazyload on our images.
Angular has made it easy and fast for us, so to achieve our aim we will be using Angular ng-lazyload-image
Api . Run the code below to install the ng-lazyload-image
.
npm install ng-lazyload-image
ng-lazyload-image
uses an intersection observer by default so you don’t need to do anything if you want to continue using the intersection observer as event emitter. Open app.module.ts and import LazyLoadImageModule and intersectionObserverPreset.
import {
LazyLoadImageModule,
intersectionObserverPreset
} from "ng-lazyload-image";
@NgModule({
declarations: [],
imports: [
LazyLoadImageModule.forRoot({
preset: intersectionObserverPreset
})
],
providers: [ApiService],
bootstrap: [AppComponent]
})
export class AppModule {}
open app.gallary.component.html.
<img alt="" [lazyLoad]="item.urls.regular" class="lazy-loading" />
The [lazyLoad] attribute on the image tag is placeholder attributes containing the URL for the image we’ll lazyload once the element is in the viewport.
Conclusion
We were able to learn how to use unsplash Api, and How to implement Lazyloading. It was a cool project to work on.
Thanks for reading. If you’ve enjoyed this article or found it useful, please share the article and leave a star on the Github Repo.