Is there a way to verify in Angular whether an image link has a width and height exceeding 1000?

I'm currently working on a function that checks if an image linked in an input field has a width and height greater than 1000 pixels, and is in JPG format.

Here's my approach:

HTML:

<input (change)="checkValidImage(1, product.main_photo)" [(ngModel)]="product.main_photo" required type="text" name="main_photo" id="main_photo" class="form-control">

TS:

img = new Image();

checkValidImage(targetPhoto: number, targetLink: string){

    console.log(targetLink);

    this.img.src = targetLink;

        if(this.img.width < 1000 || this.img.height < 1000 || !this.img.src.match(/jpg/)){
          this.toastrService.showToast(false,"Oops, we have a problem", "Image "+targetPhoto+" should be 1000x1000px in JPG format!");
          if(targetPhoto == 1){
            this.product.main_photo = null;
          }
        }

The issue arises when initially pasting a link to an image with dimensions over 1000 pixels and in JPG format, the function triggers the showToast function as img.width and img.height values show up as 0. However, upon pasting the same link again, everything works fine. What could be causing this inconsistency?

Answer №1

Your issue stems from attempting to retrieve the width of an empty image.

When you set this.img.src = linkAlvo, the image begins to load, which may take some time.

You must wait for the image to finish loading before checking its dimensions. The image element has a load event that can be utilized for this purpose.

img.onload = () => {
    if(this.img.width < 1000){
        ....
    }
}

Therefore, your code should look like this:

img = new Image();

checkValidImage(fotoAlvo: number, linkAlvo: string){

    img.onload = () => {

        if(this.img.width < 1000 || this.img.height < 1000 || !this.img.src.match(/jpg/)){
          this.toastrService.showToast(false,"Oops, we have an issue", "Image "+fotoAlvo+" must be 1000x1000px in JPG format!");
          if(fotoAlvo == 1){
            this.product.main_photo = null;
          }
        }

    }

    this.img.src = linkAlvo;

}

It's important to assign the load event before setting the image URL so as not to miss the loading event, especially if it occurs quickly before defining the event.

I haven't been able to test this code snippet, so there might be some tweaks needed, but this covers the main aspect that was missing in your implementation.

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

Issue: The CSS loader did not provide a valid string output in Angular version 12.1.1

I am encountering 2 error messages when trying to compile my new project: Error: Module not found: Error: Can't resolve 'C:/Users/Avishek/Documents/practice/frontend/src/app/pages/admin/authentication/authentication.component.css' in &apos ...

Invoke an ActionCreator within a different ActionCreator

Calling an ActionCreator from another file is proving to be a challenge... The products.ts file contains the ActionCreators and Reducers for Products... import { setStock } from './Store.ts'; //.... export const addProduct = (product: IProduct) ...

The art of toggling an ion-item effortlessly through a simple click of a button

I'm working on an Ionic project where I need to implement a button that displays items when clicked, and hides them when clicked again. However, using ShowDisplay() with *ngIf doesn't load anything. Is there a way to modify my DisplayF1() functio ...

Displaying a single http response in Angular

Having trouble displaying data from a single JSON response using Angular. I've set up a class for the data in interndata.model.ts export class Interndata { humidity: number; temperature: number; constructor(humidity:number, temperature:number) { ...

A critical error has occurred: RangeError - The maximum call stack size has been exceeded while trying to

After attempting to filter a list of titles using Ng2SearchPipeModule, I imported the module in app.module.ts and created a new searchbar component. searchbar.component.ts import { FirebaseService } from './../../firebase.service'; import { Ang ...

Upon initializing an Angular project from the ground up, I encountered an issue where a custom pipe I had created was not

After creating an Angular 16.1.0 application and a custom pipe, I encountered error messages during compilation. Here are the steps I took: Ran ng new exampleProject Generated a pipe using ng generate pipe power Modified the content of app.compone ...

Angular 6 and the intricacies of nested ternary conditions

I need help with a ternary condition in an HTML template file: <div *ngFor="let $m of $layer.child; let $childIndex=index" [Latitude]="$m.latitude" [Longitude]="$m.longitude" [IconInfo]="$childIndex== 0 ? _iconInfo1:$c ...

Develop an object's attribute using form in the Angular 5 framework

I am looking to create an object for a location that includes two parameters. While I can easily create an array of strings using FormGroup, I am unsure of how to create an object with two parameters nested inside it. Below is the code snippet I currently ...

Error when building Angular 9 due to missing peer dependencies

In my coding project, there is a specific npm module that has a dependency on electron. The functionality from this module is accessed within a function and only executed when necessary, allowing it to be utilized in both electron-based projects as well as ...

Creating a JWT token in Angular 2 Typescript: A step-by-step guide

Inside Component import * as jwt from 'jsonwebtoken'; var secretKey = privateKey; var accessToken = jwt.sign({ user: 'johnDoe' }, secretKey, { algorithm: 'RS256' }); I encountered the following issue. Uncaught (in promise) ...

hide elements only when there is no string to display in Angular2/Typescript

As I experiment with my javascript/typescript code, I've encountered an issue where a string is displayed letter by letter perfectly fine. However, once the entire string is shown, the element containing it disappears and allows the bottom element to ...

Manipulate and send back information from Observable in Angular

Here is an example of a scenario where I have created a service to retrieve a list of properties. Within this service, I am utilizing the map function to manipulate the response and then returning the final array as an Observable. My question is: How can ...

Unexpected INTERNAL error encountered with Firebase's Cloud Function update

Currently, I am immersed in a project involving Vue.js 3, Typescript, and Firebase. However, while attempting to integrate new cloud functions, I came across an unexpected issue: Failed to load resource: the server responded with a status of 500 () Un ...

Encountering the error "No overload matches this call" while utilizing useQuery in TypeScript may indicate a mismatch in function parameters

My issue lies with TypeScript and types. Here is the API I am working with: export const clientAPI ={ //... getOptions: async (myParam: number) => get<{ options: Options[]; courses: any[] }>(`/courses?myParam=${myParam}`)().then((result) =& ...

Filtering a multi-dimensional array in Ionic 3

I attempted to filter an array from a JSON with the following structure {ID: "2031", title: "title 1", image: "http://wwwsite.com/im.jpg", url: "url...", Goal: "3000000", …} The array is named 'loadedprojects' and below is the filteri ...

Tips for adding a new property to an array object in TypeScript using a condition

Here is an array object that I have: arr = [ { Name: "ABC", Age: 20}, { Name: "XXX", Age: 15} ]; In Typescript, I am looking to dynamically add a new property called "Flag" with a value of 1 only if the Age is greater than 15. Can someone suggest ...

Having trouble with showing dynamic data in column2 of my HTML layout, and the alignment doesn't look quite right in HTML

I'm working with this HTML file, attempting to create a two-column layout using HTML and CSS. I want one column to be labeled REQUEST and the other RESPONSE. When a value is entered in the text field in Column 1, it should display a response in Column ...

Slow appending of child elements within an Angular view container reference

Using createElement, I am creating a wrapper div to contain a dynamically created component that will display a tool tip using Leaflet's bindPopup function. However, I am facing a delay in appending the child component to the wrapper. As a result, the ...

What causes images to unexpectedly expand to fill the entire screen upon switching routes in Next.js?

I'm in the process of creating a website using Next and Typescript, with some interesting packages incorporated: Framer-motion for smooth page transitions Gsap for easy animations One issue I encountered was when setting images like this: <Link&g ...

Data can be retrieved in a React/Next.js application when a button is clicked, even if the button is located in a separate

Whenever the button is clicked, my function fetches weather data for the current location. I am trying to figure out how to transfer this data from the Location component to the pages/index.tsx. This is where another component will display the data. This ...