Adding multiple styles using ngStyle is currently not possible

When using ngStyle to add height and width styles to an img element, I encountered a strange issue:

<img class="image-full-view" [ngStyle]="{'height': selectedImage.heightSize, 'width': selectedImage.widthSize}" [src]="selectedImage.imagePath" alt="Man Praying"> 

The image data is fetched from an object within a service file:

 private images = [
        new Image('Man Praying', 1, 'Cambodia', 'Man praying to Sun', '£100', '../../assets/Images/Cambodia/Praying to the Sun.JPG', '250px', '800px'), 
]

The height is set to 250px and the width to 800px.

In a separate model file, the object constructor is defined as follows:

export class Image {
public name: string;
public id: number;
public album: string;
public description: string;
public price: any;
public imagePath: string;
public heightSize: any;
public widthSize: any;


constructor(name: string, id: number, album: string, description: string, price: any, imagePath: string, heightSize: any, widthSize: any) {
    this.name = name;
    this.id = id;
    this.album = album;
    this.description = description;
    this.price = price;
    this.imagePath = imagePath;
    this.heightSize = heightSize;
    this.widthSize = widthSize;
}
}

Interestingly, while the height style gets applied correctly, the width does not. Upon inspecting the element with Chrome dev tools, only the height style is present. Could there be something missing in my code that's causing this discrepancy?

This is how the element appears in Chrome dev tools:

<img _ngcontent-vxx-c18="" alt="Man Praying" class="image-full-view" ng-reflect-ng-style="[object Object]" src="../../assets/Images/Cambodia/Praying to the Sun.JPG" style="height: 250px;">

I have thoroughly checked my code to ensure that no other stylesheet is overriding the width of the image. Any insights on what might be causing this issue would be greatly appreciated!

Answer №1

If you want to apply multiple ngStyles, you can create a method that returns them:

HTML:

[ngStyle]="getImageStyles()"

TS:

getImageStyles(): object {
    return {
        height: this.image.heightSize ? this.image.heightSize : '',
        width: this.image.widthSize ? this.image.widthSize : ''
    };
}

Answer №2

It appears that the error was caused by a missing semicolon in the object constructor:

export class Image {
    public name: string;
    public id: number;
    public album: string;
    public description: string;
    public price: any;
    public imagePath: string;
    public heightSize: any;
    public widthSize: any;


    constructor(name: string, id: number, album: string, description: string, price: any, imagePath: string, heightSize: any, widthSize: any) {
        this.name = name;
        this.id = id;
        this.album = album;
        this.description = description;
        this.price = price;
        this.imagePath = imagePath;
        this.heightSize = heightSize;
        this.widthSize = widthSize;
    }
}

Following Bryan's recommendation:

    export class Image {

    constructor(
        public name: string,
        public id: number,
        public album: string,
        public description: string,
        public price: any,
        public imagePath: string,
        public heightSize: any,
        public widthSize: any) {}
}

A simple oversight!

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

Double-executing methods in a component

I have encountered an issue while trying to filter existing Worklog objects and summarize the time spent on each one in my PeriodViewTable component. The problem I am facing involves duplicate method calls. To address this, I attempted to reset the value ...

Morris.js tutorial: Enhancing bar charts with data labels

I have this: https://i.sstatic.net/GXjur.png But I want this instead: https://i.sstatic.net/spcS2.png Does morris.js support this feature? If not, what would be the most effective method to implement it? ...

Ways to access the value of the parent observable?

I've been exploring the concept of nesting HTTP requests using mergeMap. The API I'm working with sends data in parts, or pages, which means I have to make more requests based on the total number of pages. To determine the number of pages, I alw ...

Instead of tapping the enter key, try searching by keying up

I am implementing a search pipe in Angular for filtering data based on user input import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'searchPipe', pure: false }) export class SearchPipe implements PipeTransform { ...

Create a PDF document utilizing Angular Ignite UI for Angular

Currently working with Angular TypeScript 12, I have successfully integrated Angular Ignite UI grid. However, I am in need of a way to export my grid into a PDF format using Igx-Grid. Does Igx-Grid support PDF exporting? If not, are there any alternative ...

Covering the full width of the page, the background image

My struggle is with setting a background image to 100% width, as the image ends up getting cut off on half of the screen. The picture becomes wider than my display area. How can I resolve this issue so that the image width adjusts to fit the screen without ...

What is the best way to remove table row data fetched from an API within a table?

Can someone assist me with deleting the table tr from the user table, where data is retrieved from an API? I have attempted the code below: $("principleTable").find("tr").hide(); $("#delAgentModal").modal("hide"); ...

encase the text within a div to create a visual flow

Is there a way to make div 2 encircle div 1? Both divs have text inside. +---++------------------+ | || | | 1 || | | || 2 | +---+| | +---- | | | ...

Why does my anchor disappear after a second when clicked to show the image?

Hi everyone, I'm having an issue with a dropdown menu that I created using ul and anchor tags. When I click on one of the options, an image is supposed to appear. However, the problem is that the image shows up for just a second and then disappears. I ...

Generating values in a loop - mastering the art of creating data points

My goal is to create a variable within a loop: box-shadow: 835px 1456px #FFF, 1272px 796px #FFF, 574px 1357px #FFFand so on... The concept is simple: box-shadow: x1 y1 #fff, x2 y2 #fff, x3 y3 #fff, x4 y4 #fff ... xn yn #fff. I attempted to achieve this ...

The class styling is malfunctioning

When I click the 'night' button, I want the word color in the class=css to change to white. However, this is not working as intended, even though all other word colors are changing correctly. Here is my code: .css { font-weight: bold; ...

What is the method to adjust the color of <pagination-controls>?

Seeking assistance with customizing the color of angular pagination from blue to a different hue. Any suggestions? https://i.stack.imgur.com/JjcWk.png I've experimented with various code snippets, but unfortunately, none have yielded the desired res ...

Experiencing a snag with Angular2 and angular2-jwt: encountering an issue with AuthHttp where the JWT must consist

Encountering an issue with AuthHttp despite receiving a valid token from the authentication. The token has been confirmed as valid on . Currently working with Angular 4. Here is my code: Sign-In Code signIn(login: string, password: string) { this.U ...

Passing Selected Table Row Model Data to Backend in Angular 7

My goal is to send the selected data in a table row, which I select through a checkbox, to the server. However, I'm unsure about how to handle this via a service call. While I have the basic structure in place, I need assistance with sending the items ...

Angular Issues: Problems with Saving Data to Local Storage

Encountering 2 bugs in the methods responsible for saving products to local storage when users add them to their 'favorites' list. The code pertains to an Angular service but can be understood independently of this framework. Bug #1: Occasional ...

Tips for positioning an asp.net Button alongside other elements in a form by making use of Bootstrap styling

Looking to revamp the style of my ASP.NET Web Forms project with the latest version of Bootstrap. Having trouble aligning an ASP.NET Button control horizontally with other controls in the form, as seen in this snapshot: https://i.sstatic.net/IVRKo.png Her ...

Can multiple Observables be used to display FormArray data within a FormGroup effectively?

I've spent countless days attempting to asynchronously display dynamically loaded FormArray data without success. Essentially, I have a FormGroup that is created on click and shown in a modal window (no issues with displaying data loaded in the subscr ...

Scrollspy in Twitter Bootstrap consistently highlights the final element

I'm struggling to understand why only the final section is being highlighted when scrolling. Can you help? <body data-spy="scroll" data-target="#homeToolbar" data-offset="50"> <nav class="navbar navbar-default navbar-fixed-top" id="homeToo ...

Move the cursor to the end of the text when the key is released

I've developed a feature similar to that of a command line interface. When you input commands and hit the up key, the previous command is displayed. Everything is functioning as intended, but there's one minor issue. The current problem I'm ...

Develop an outline using D3.js for the clipath shape

After successfully creating a shape with a color gradient, I encountered the need for further customization. If you are interested in this topic, check out these related questions: Add multi color gradient for different points in d3.js d3.js scatter plot c ...