Discover the unseen: The ultimate guide to detecting visible objects in a (deferLoad) event

I'm utilizing the (deferLoad) method to load an image gallery in a more controlled manner. Is there any event available that can inform me about which items are currently visible?

The main goal is to load a set of data along with an image path, and then trigger the loading of the image when the item becomes visible.

Is there a way to determine which products are visible so that I can send their images to an API, either through an event or some other method?

Check out the Demo

.TS

<ul class="mdc-image-list my-image-list first">
    <li class="mdc-image-list__item" style="height:200px" *ngFor="let image of Images; let i = index"
        (deferLoad)="image.show = true">
        <ng-container *ngIf="image.show">
            <img [src]="image.url" style="height: 100%;width: 100%;">
            <div class="mdc-image-list-supporting"
                style="display: flex; align-items: center;flex-direction: column;padding: 2px">
                <span class="mdcImageListLabel">{{image.name}}</span>
            </div>
        </ng-container>
    </li>
</ul>

Answer №1

If you're looking to implement lazy loading of images in Angular, the IntersectionObserver API can be a useful tool. One way to achieve this is by creating a directive specifically for handling lazy loading:

@Directive({
  selector: '[lazySrc]'
})
export class ImgDataDirective implements OnInit, OnChanges {
  @Input('lazySrc') src: string;

  constructor(
    private _elRef: ElementRef,
    private _renderer: Renderer2,
    @Inject(PLATFORM_ID) private platformId: Object
  ) {}

  ngOnChanges(changes: SimpleChanges): void {
    this._loadImage();
  }

  ngOnInit(): void {
    this._renderer.setAttribute(this._elRef.nativeElement, 'src', PLACEHOLDER);

    if (isPlatformBrowser(this.platformId)) {
      const obs = new IntersectionObserver(entries => {
        entries.forEach(({ isIntersecting }) => {
          if (isIntersecting) {
            this._loadImage();
            obs.unobserve(this._elRef.nativeElement);
          }
        });
      });
      obs.observe(this._elRef.nativeElement);
    }
  }

  private _loadImage() {
    this._renderer.setAttribute(this._elRef.nativeElement, 'src', this.src);
  }
}

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

Inversify: class-based contextual dependency injection

I am currently experimenting with injecting loggers into various classes using inversify. My goal is to pass the target class name to the logger for categorization. The challenge I'm facing is the inability to access the target name from where I am c ...

What is the best way to check for duplicate email input when using knex?

Currently, I am in the process of developing an application using node.js, knex.js, typescript, zod, and fastify. My main focus is on validating emails during user registration. If a duplicate email is inserted, I want the system to throw a 401 (conflict) ...

Issues encountered with asp.net javascript function not executing

Having trouble getting a javascript function to execute via jquery in an asp.net setting. Despite trying various approaches, the function doesn't run upon clicking the button. I've experimented with omitting jquery and using a static html input c ...

Angular 2 routing malfunctioning

I'm encountering an issue while setting up routing in my application. The error displayed in the console is as follows: angular2-polyfills.js:138 Error: XHR error (404 Not Found) loading http://localhost:9000/angular2/router.js(…) Below is the co ...

The issue encountered with the Material UI Autocomplete component is that it is not displaying the values

I'm currently attempting to extract a value from the state to be used in materialUI's autocomplete component. However, I've encountered an issue: The autocomplete feature works perfectly when selecting a value and saves it to the state wit ...

Can JavaScript bypass the need for an html page and go directly to the printing process?

Is it possible for a user to click a "print" button and have the printer start printing? Please note that there is already a server process in place (via AJAX) that can respond with success for printing or return HTML content for display, so that is not a ...

Struggling to make dynamically created SVG 'use' elements function properly

SVG offers a unique system with symbol and use where icons can be defined once and reused throughout the SVG using use. However, I am having trouble getting it to work from JavaScript. You can view an example on this JSFiddle link. When programmatically ...

Executing a Playwright test against various projects or URLs within a single test run

I've been grappling with this problem for the past few days. I've tried a few workarounds, but none of them have worked as expected. What I need is to run Playwright tests against multiple URLs. Currently, running tests in a single project works ...

Accessing the locally stored data and displaying it in ng-bind

My journey to learn javascript through this project has hit a roadblock. I have stored an exchange rate in local storage: localStorage.gbpUSD = "1.42746"; Now, I want to utilize it instead of the hardcoded exchange rate in the code below... <input t ...

Tips for combining Bootstrap 5's .is-invalid class with Angular's ng-invalid attribute

Bootstrap 5 provides a convenient way to indicate invalid input fields using the .is-invalid class. https://i.sstatic.net/UkgkU.png While working with a reactive form, I noticed that the "ng-invalid" style is applied when an input field is considered "in ...

Leveraging Vuex stores in a modular WebPack setup

I am currently working on a web application where each page of the site has 2 JS files: a global "bootstrap.js" file that is consistent across every page and a custom JS file specific to each page. I've run into an issue where I want these files to sh ...

Unraveling the mystery: accessing the same variable name within a function in JavaScript

What is the best way to reference the same variable name inside a function in JavaScript? var example = "Hello"; console.log("outside function: " + example) function modifyVariable() { var example = "World!"; console.log("inside function: " + ex ...

After downloading the latest version of NodeJS, why am I seeing this error when trying to create a new React app using npx?

After updating to a newer version of NodeJS, I attempted to create a new React app using the command npx create-react-app my-app. However, I encountered the following error message: Try the new cross-platform PowerShell https://aka.ms/pscore6 PS E:\A ...

Modify an element on one webpage using a function called from another webpage

I am currently working on a website design that involves displaying images on various frames. While I have managed to change content across different frames, I am now exploring the possibility of changing content across different web pages. Here is the se ...

In what way can you dynamically set the displayName using a higher order component?

My current struggle is setting displayName dynamically in order to improve the debugging process. Each component renders as <Component ... />, making it difficult to identify them in the codebase. While I have successfully set static displayName on e ...

Troubleshooting AngularJS application by Manipulating List Items

Having trouble debugging Angular lately. It feels like things are breaking and fixing themselves magically. For instance, I had an ajax call to delete a "site" which was working fine until I decided to add some code to remove it from the list as well. Now, ...

Why is it that useEffect is functioning correctly only on the first occasion?

Recently, I've been facing significant challenges with React's useEffect and States. The issue arises when I redirect to the main page of my app and then attempt to use them again. In the following component, everything seems to function correct ...

Alter the color of a single character using JQuery, all while keeping the HTML tags unchanged

I'm currently working on iterating through the DOM using JQuery in order to change the color of every occurrence of the letter m. Here is what I have so far: $(document).ready(function(){ var m = "<span style='color: red;'>m</span& ...

How can you ensure that the Data Point Values are always displayed when using arrayToDataTable in the Google Charts API?

Just wanted to clarify that even though there is a similar question titled: Google Charts API: Always show the Data Point Values in Graph ...on this website, I am facing difficulties implementing its solution because my chart is using arrayToDataTable. ...

Angular 13: Problems arise with custom theme in Angular Material version 13

I've set up a custom theme palette for my project that works perfectly with version ^12.2.13 of Angular Material, but not with ^13.2.3. Here's the SCSS code for my custom theming: my-custom-theme.scss @import '~@angular/material/theming&apo ...