Angular: Tips for retrieving image dimensions before rendering it in the DOM

I'm new to the world of Angular and Typescript, so please forgive me if this question seems silly.

In my single-image view component, I have an Array of image urls/meta-data that are loaded from a local .json file by a service:

...
<img [src]="my_picture.large" [alt]="my_picture.title">
...

Before loading my_picture.large into the DOM, I would like to gather more information about it. Is there a way to do this? For example, I want to know its width, height, aspect ratio, and then react accordingly with different templates depending on whether it is portrait or landscape.

Adding meta information to the json file is an option, but as I am still learning, I am trying to find the best Angular approach to problem-solving. :)

On a related note, is it possible to pre-load images before displaying them on the DOM?

Answer №1

Give this a shot:


    function getImgDimensions(url) {
        const image = new Image();
        image.onload = function() {
            console.log(this.width, this.height);
        };
        image.src = url;
    }

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 with Angular not rendering data retrieved from HTTP response

In my Service script class, I have defined a HomeApiService with the following code: export class HomeApiService{ apiURL = 'http://localhost:8080/api'; constructor(private http: HttpClient) {} getProfileData():Observable<HomeModelInterface[ ...

Error in Angular 2: Component unable to locate imported module

I'm facing an issue where a module I want to use in my application cannot be found. The error message I receive is: GET http://product-admin.dev/node_modules/angular2-toaster/ 404 (Not Found) The module was installed via NPM and its Github reposito ...

Issue with Angular authentication during login attempt

I am a beginner in Angular and I'm using this method to allow users to log into the system. loginuser(){ const user = { username: this.username, password: this.password }; this.Auth.loginUser(user).subscribe((res)=>{ ...

Synchronization problem encountered in an Angular app involving playwright

Currently, I am working on automating a process where the service queries the database and displays the data on the user interface. However, the rendering takes a considerable amount of time, around 3 minutes. Despite using Playwright for automation, it do ...

After introducing 5 guard properties, the intersection of unions in Typescript breaks down

In TypeScript, I am attempting to create a class where properties are only accessible if another property has been checked on the class. This needs to be done in a generic manner to facilitate reuse across multiple classes. For instance, class Test { Fo ...

When implementing Swiper in TypeScript, an error is encountered: TypeError - Attempting to invoke the Swiper class constructor without using the 'new' keyword

I am facing an issue for which I couldn't find a solution, so I'm attempting to solve it myself for the first time. I am using TypeScript and Next.js, but unfortunately, Swiper does not offer direct support for Next.js and TS. Below is the TypeS ...

Setting up Typescript error handling for next-auth getProviders configuration

I recently started learning Typescript and came across a tutorial using next-auth. However, I encountered an error while following the tutorial with Typescript when using the getProviders function. https://i.stack.imgur.com/H5LaL.png https://i.stack.imgu ...

The functionality of Angular JSON browserTarget has been deprecated and is no longer supported

I encountered a warning where 'borwserTarget' was deprecated in my Angular JSON file. Instead of using 'browserTarget', it prompted me to use 'builtarget'. However, it states that the data path must have a required property &a ...

When using TypeScript with Jest or Mocha, an issue arises where the testing frameworks are unable to read JavaScript dependencies properly, resulting in an error message saying "unexpected token

Currently, I am conducting testing on a TypeScript file using Mocha. Within the file, there is a dependency that I access via the import statement, and the function I need to test resides within the same file as shown below: import { Foo } from 'foo- ...

`The Art of Curved Arrows in sigjma.js, typescript, and npm`

I have encountered an issue while trying to draw curved arrows in sigma.js within my TypeScript npm project. The error occurs on the browser/client-side: Uncaught TypeError: Cannot read properties of undefined (reading 'process') at Sigma.pro ...

Guide to transforming a TaskOption into a TaskEither with fp-ts

I have a method that can locate an item in the database and retrieve a TaskOption: find: (key: SchemaInfo) => TO.TaskOption<Schema> and another method to store it: register: (schema: Schema) => TE.TaskEither<Error, void> Within my regis ...

Tips for simulating behavior in express using Typescript and the Mocha library

Help with mocking 'Request' in Mocha using express with Typescript needed! Here is the current approach: describe("Authorization middleware", () => { it("Fails when no authorization header", () => { const req = { ...

Issue: When attempting to read the length of a property in Angular 6, a TypeError is being thrown because the property is

Unable to retrieve values from an array using the TS code below: this.dataservice.get("common/public/getAllCategories", null).subscribe(data => { //console.log('categories'+JSON.stringify( data)); this.categoriesarray = data; }); var ...

`ngCustomTranslation` - automatically defaults to `English` if no other language is specified

Currently, I am utilizing ng2-translate for language translation. However, even after changing the language setting, the translation still defaults to en. Ideally, I want it to switch to fr, but my default language is not loading at all. Below is a snippet ...

Navigating in Angular with parameters without modifying the URL address

In a nutshell, my goal is to navigate to a page with parameters without showing them in the URL. I have two components: Component A and B. What I want to do is route to B while still needing some parameters from A. I know I can achieve this by setting a ...

Error: Ionic 2 encountered an error: Highcharts has produced Error #17 - learn more at www.highcharts.com/errors/17

I'd like to incorporate a highchart gauge in my project, but I'm encountering an issue: Uncaught (in promise): Error: Highcharts error #17: www.highcharts.com/errors/17 error I've been advised to load the highcharts-more.js file, but I&a ...

Animating Page Transitions using Angular 2.0 Router

Seeking to implement animated transitions for new components using the onActivate method in Angular 2. A Plunk has been set up to demonstrate the issue at hand: http://plnkr.co/FikHIEPONMYhr6COD9Ou Here is an example of the onActivate method within a pag ...

Tips for positioning the border properly within a scrollable table

My table has a sticky header with a fixed height, and in order to see more rows in the table, we have to scroll through them. The table design includes borders. The problem arises when there are more rows, as the border moves with the scroll. Initially, ...

What is preventing me from consistently accessing the Type Definition while my cursor is on a JavaScript/TypeScript parameter name in VS Code, and what are some strategies I can use to overcome this issue?

Imagine I have the following code snippet in my VS Code: type T1 = { x: number }; type T2 = { x: number } & { y: string }; function foo(arg1: T1, arg2: T2) {} If I place my cursor on arg1 and go to the type definition (either through the menu or a sh ...

What are the steps for transforming my 2D array to fit a specific schema using RxJS?

UPDATE I stumbled upon a potential solution that I have appended to my question and am now seeking a more refined approach. In the context of an Angular 9 application, I am working with a two-dimensional array that I need to restructure. Through my use of ...