Loading images from Contentful in Angular 8 using Resolve before rendering them on the view

I am currently facing a challenge that I need help with:

https://i.sstatic.net/ytLoj.gif

The issue I am encountering is that when the page loads, the view renders before the images fully load. Is there a way to ensure that the view only renders once the images have completely loaded? It's worth mentioning that the images are hosted on a different domain, specifically on Contentful.

I've been exploring the Resolve API as a solution, but I'm struggling with implementing it since I'm not making an HTTP request.

Below is my attempt at creating a resolve service:

export class GalleryImagesResolverService implements Resolve<any> {
  
  constructor(
    private contentfulService: ContentfulService
  ) { }

  resolve(route: ActivatedRouteSnapshot) {
    return this.contentfulService.getGalleryImages();
  }
}

Here's the contentful service code snippet:

//get Gallery Images
getGalleryImages(query?: object): Promise<Entry<any>[]> {
return this.cdaClient.getEntries(Object.assign({
// include : 2,
content_type: CONFIG.contentTypeIds.gallery
}, query))
.then(res => res.items);
}

Any advice or suggestions would be greatly appreciated! If you have a better approach in mind, please share your insights. :)

Answer №1

As mentioned by "Sangwin Gawande," the (load) eventListener in HTML can help achieve this functionality.

To simplify this process, I have created a helpful component to handle loading of images:

Child Component

import { Component, Input } from '@angular/core';

@Component({
  selector: 'img-with-loader',
  template: `

    <div *ngIf="loading">
      LOADING CONTENT GOES HERE
    </div>
    <img
      [hidden]="loading"
      [src]="imgSrc"
      (load)="loading = false"
    />
  `
})
export class ImgWithLoaderComponent {
  @Input()
  imgSrc: string;

  loading = true;
}

Parent Component

Replace the regular <img> element with the following code to prevent displaying the image until it finishes loading:

<!-- background won't show until the image is finished loading -->
<img-with-loader [src]="backgroundUrl"></img-with-loader>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular2 with Bootstrap Grid integration is a powerful combination for building

Struggling to implement bootstrap's grid layout system in Angular2 with a list of objects. Any tips or guidance would be greatly appreciated! If I was using HandlebarsJS, I could achieve this layout with the following code: {{#for elements}} {{# ...

How can I send a value from a for loop to a URL within a modal using Django?

Currently, I am working on a project that involves using a for loop with buttons and their corresponding pk values. {% for obj in all_objects %} <button data-toggle="modal" data-id="{{ obj.pk }}" data-target="#myModal" class="open-my-modal"> {{ ob ...

The 'fetch' operation could not be completed on the current window due to a TypeError

The error message I am receiving is: TypeError: Failed to execute 'fetch' on 'Window' : The provided value is not of type '(sequence<sequence> or record<ByteString, ByteString>)'. My current challenge involves fetc ...

Waiting to submit a Vue form until a field is filled out

I am working on a Vue application. I have a form with a button that, when clicked, should fill the input field with the value paypal and then submit the form. However, when I check the variable $_POST['paymentMethod'] in the file test_form.php, i ...

Guide to automatically send a message when a new channel is added to a designated category using discord.js

Looking to develop a JavaScript Discord bot that automatically sends a message to new channels created under a designated category. The goal is to have the same message sent to every newly created channel. Seeking assistance from anyone knowledgeable on h ...

What is the best way to extract information from a table that has been populated by a backend function?

My current task involves extracting data from a table that loads its rows slowly from a back-end ASP.NET function call. This table contains dimensions, with each row including the dimension name, database connection, an assigned checkbox, key field, and ...

Having trouble passing variables via URL when using PHP and AJAX

I've encountered an issue while using AJAX to automatically update a web page every 5000 milliseconds. The problem arises when trying to retrieve data from the URL using $_GET or $_POST, as it only returns a value of 1. Below is an example code snippe ...

Show items in a row inside a div

This section is about a specific div element: <div class="PictureContent1" style="display:inline-block" value="1"> </div> Here is the actual content: for(var i = 0; i<ui.item.productpictureurl.length; i++){ $(&ap ...

Avoid allowing users to copy text by dragging and dropping it from the browser

I am looking for effective ways to prevent users from easily copying text from my website. After doing some research, I came across a useful solution here This method successfully prevents copy/paste/cut actions when using ctrl key combinations and the r ...

Solutions for accessing data variables outside of a Vue file

Utilizing Vue.js for data binding and filtering has been a rewarding experience. I've set up a Vue object within a .js file and now I aim to pass external data into it. Let's take a look at my test object testFile.js: var vm = new Vue({ el: ...

The issue with ag-grid not displaying data when the column configurations are changed dynamically

I have been working with ag grid to display data in my component. I am fetching data through an API call and dynamically extracting the column names from the response to pass this information to the child component for display. However, the data is not sho ...

creating a post action using Node.js with Express and Angular

Process Overview I have an Angular post that communicates with my Node.js Express backend to send data to an API. My goal is to redirect the user to a different Angular page upon successful post, or display an error message if the post fails. One approac ...

Encountered a JSON.Parse error in Angular 9's HttpErrorResponse even though the response was successful

Why am I encountering an error with this code snippet? deleteUser(userId: string) { this.dataService.deleteUser(userId).subscribe((response: string) => { console.log(response); }); } "SyntaxError: Unexpected token f in JSON at p ...

When dealing with a react input field, the term " synthetic" keeps popping up after every attempt to save changes. Additionally, using "value" instead of "defaultValue"

As a beginner in development, I'm encountering issues when trying to save changes on my input field. I keep receiving an error message that reads: "Warning: This synthetic event is reused for performance reasons. If you're seeing this, you'r ...

Creating a curved edge for a shape in React Native can add a stylish and

Issue Description I am working on an app and struggling with styling the bottom navigation bar. It's more complex than what I've done before, especially the curved top edge of the white section and the area between the blue/green circle and the ...

Move the creation of the HTML string to an HTML template file within ngx bootstrap popover

I have incorporated ngx bootstrap in my project through this link To display dynamic HTML content in the popover body, I am using a combination of ngx-bootstrap directives and Angular template syntax as shown below: <span *ngFor="let item of items;"&g ...

Error message: Icons failing to display in conjunction with template output | 404 error code

I'm trying to display icons based on a search, but I keep getting a 404 error for http://localhost:3000/static when I input a value. My current folder structure looks like this: Root directory > Public > Icons and Root directory > index.js. ...

Leverage the power of Node.js by utilizing http.get along with

I have been working on integrating a library (available here) into my project, which is capable of generating QR codes and various other types of codes. My current issue revolves around making a request where I can access both the req and res objects in o ...

Utilizing props for toggling the navigation list, incorporating nested arrays or objects

My issue involves two components that are loading data. I want the links to be output like this: group1 linka linkb However, they are currently displaying like this: group1 linka group1 linkb I believe the problem lies in how I am handling the ...

Issue Encountered in NodeJS While Processing Multiple GET Requests

I have been developing a web application that utilizes a database containing game data. When a user clicks on a game, a GET request is made to an API to retrieve additional information for the selected game. My goal is to ensure that users can access detai ...