Creating a New Project
Explore how to set up a new Angular project focused on directives by creating an image gallery with pagination. Learn to install Bootstrap for styling, add image data, and use the ngFor directive to loop through images and create navigable pagination controls.
We'll cover the following...
The next project we’ll work on will display a set of images with pagination. The main focus of this section is to learn about directives. First things first, we’ll prepare a new project.
New project
If you’re running code locally, then you’ll need to run the following command:
ng new directives
During the setup process, you’ll be asked to configure the project. Go with the default settings.
Installing Bootstrap
After installing the project, navigate to the newly created directory, and install Bootstrap. We’ll be using it to help us with styles. You can run the following command to install Bootstrap:
npm i bootstrap
We’ll need to update the styles.css file to import Bootstrap.
@import "bootstrap/dist/css/bootstrap.css"
Adding data
The next thing we’ll do is add the set of images we’ll be using in the application. If you’d like, you can download some of your favorite and upload them to the assets directory. Alternatively, you can provide a direct link to them. There are two sites where you can grab royalty-free images: Unsplash and Lorem Picsum.
Once you’ve retrieved your images, we’ll update the app.component.ts file to define a property called images. Each item in the array will be an object with two properties: title and url. The title property will be dummy text, and the url property will be the URL to the image.
Looping through the images
The last step is to output some links for navigating through the collection of images. We’ll use the ngFor directive to accomplish this. Update the app.component.html file to the following:
The example above is using Bootstrap’s pagination component. You can find more information here: https://getbootstrap.com/docs/5.0/components/pagination/.
There are three links. The first and last links are for moving to the previous or next image. The second link will be looped through to output a link to a direct item in the collection of images. We’re using the ngFor directive for this.
Each item in the iteration is assigned an alias of img. We’re also capturing the index. It has an alias of i.
Lastly, we’re outputting the index plus 1. The reason we’re adding 1 is that arrays are zero-indexed. The first item in the array has an index of 0, but most people typically start reading at 1. We’re bumping the index to make the buttons easier to understand.
Here’s the project with the modification we made in this lesson:
<ul class="pagination">
<li class="page-item">
<a class="page-link" href="#">Previous</a>
</li>
<li class="page-item" *ngFor="let img of images; let i = index;">
<a class="page-link" href="#">{{ i + 1 }}</a>
</li>
<li class="page-item">
<a class="page-link" href="#">Next</a>
</li>
</ul>