Ways to transfer JavaScript arguments to CSS style

Currently, I am developing a web service using Angular and Spring Boot. In this project, I have implemented cdkDrag functionality to allow users to place images in specific locations within the workspace. My goal is to maintain the placement of these images even after a browser refresh. To achieve this, I am saving the coordinates of each image in the database after every drag and drop action. When the browser is refreshed, I retrieve the previous coordinates from a Router class:

export class Router implements Node {

  id: string;

  x: number;
  y: number;

  constructor() {
  }
}

Here is some HTML code related to this process:

<mat-sidenav-content>
    <a *ngFor="let router of routers">
      <img id="node" src="assets/images/router.png" cdkDrag (click)="updateParameters($event, router)">
    </a>
</mat-sidenav-content>'

My intention now is to dynamically set the margin-left property as router.x + "px" and margin-top property as router.y. However, my initial attempt using

style="margin-left: {{router.x}}px"
did not produce the desired result. Does anyone know if there is another approach to achieving this?

Answer №1

To achieve this, utilize the ngStyle directive.

NgStyle is an attribute directive that can be used to update styles for the surrounding HTML element. It allows you to set one or more style properties using colon-separated key-value pairs. The key represents the style name and can include a . suffix (e.g., 'top.px', 'font-style.em'). The value should be an expression that will be evaluated. If the result of the evaluation is not null, it will be assigned to the corresponding style property in the specified unit. If the result is null, the style will be removed.

<some-element [ngStyle]="{'margin-left': router.x + 'px'}">...</some-element>

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

What is the process for obtaining the result and storing it in an array using M

Recently, I just started exploring angular and ventured into using mongoose with mongodb. Within my application, I require a list of driver names in the form of a string array. However, instead of receiving a simple array of names, I am getting an array o ...

What is the best way to remove top divs without causing the bottom divs to shift upwards?

I am faced with a scenario where I must remove the topmost divs in a document without altering the user's view. Essentially, I need to transition from: ---------start of document div1 div2 div3 ---------start of window div4 div5 ------- ...

What steps should I follow to integrate the NextUI Tab component in my NextJS project?

Hi everyone, I am new to NextJS. I recently set up a basic NextJS starter project with NextUI by using the command npx create-next-app -e https://github.com/nextui-org/next-app-template. Now, I am trying to add a tab group with 3 tabs to the default page. ...

Utilize CSS to break through a backdrop

I have come across a rather peculiar question, and I'd like to elaborate with a code snippet: .container { width: 200px; height: 200px; background: rgba(200, 200, 200, .87); } .pin { position: absolute; left: 50px; top: 20px; } .overl ...

Simulated custom error response object jasmine-Angular

Within the HTTP service, there is a single function designed to manage all HTTP errors, taking custom objects and displaying errors based on specific conditions. This is an example of the service function: get(path: string, params: HttpParams = new Http ...

Align two grid columns in the centre of the footer

I have a question regarding the alignment of two grid columns in my footer. I am using Bootstrap 4 and would like to center them directly in the middle. Currently, both columns are centered individually but there is a large space between them. I have tried ...

Leverage the power of JSON values by incorporating them directly into HTML tags

My JSON file is generating the following styles: { "h1" : { "font-family" : "Lato", "font-size" : "24px", "line-height" : "28px", "font-weight" : 600, "colorId" : 3, "margin-bottom" : "10px", "margin-top" : "20px" }, "h2" : { ...

The error message "ng2-test-seed cannot be found - file or directory does not exist"

I've been attempting to work with an angular2 seed project, but I'm encountering some challenges. https://github.com/juliemr/ng2-test-seed When I run the command: npm run build I encounter the following error: cp: cannot stat ‘src/{index.h ...

Show categories that consist solely of images

I created a photo gallery with different categories. My goal is to only show the categories that have photos in them. Within my three categories - "new", "old", and "try" - only new and old actually contain images. The issue I'm facing is that all t ...

Styling images side by side with CSS in Internet Explorer

I've encountered a CSS dilemma. I have a collection of images that I want to present side by side using an unordered list within a fixed width container. The goal is to have 3 images per row before moving on to the next set of 3 images. Each list ite ...

Words of wisdom shared on social media

How can I share text from my HTML page on Twitter? This is the code snippet from my HTML page - function change() { quotes = ["Naam toh suna hi hoga", "Mogambo Khush Hua", "Kitne aadmi the?"]; auth = ["Raj", "Mogambo", "Gabbar"]; min = 0; max = ...

Transforming an Observable to a boolean using RXJS

Hey there, I'm currently working on creating a function similar to this: verify(){ return this.http.post(environment.api+'recaptcha/verify',{ token : this.token }).pipe(map(res=>res.json())); } I want to be able to use ...

Updating the text of an element will occur only when the specified condition has been met

I am trying to dynamically change the text within the <span data-testid="recapItemPrice">ZADARMO</span> element from 'ZADARMO' to 'DOHODOU' only when the text inside the parent element 'INDIVIDUÁLNA CENA PREP ...

dropdown menu items with jQuery toggle feature

Having an issue with a jQuery dropdown menu. Below is the code: $('.item-active, .item').click(function() { $(this).toggleClass('item-active'); if($('h3').hasClass('item-active')) { $(this).siblings ...

Sending a style prop to a React component

My typescript Next.js app seems to be misbehaving, or perhaps I'm just not understanding something properly. I have a component called <CluckHUD props="styles.Moon" /> that is meant to pass the theme as a CSS classname in order to c ...

Encountering a CORS problem following a successful API request within an ABP application

Access to XMLHttpRequest at 'serversiteurl//api/services/app/QklyProcessEngine/CallProcess' from origin 'clientsiteurl' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resou ...

Is there a way to open a link in a new window without using the _blank attribute?

I am facing an issue where I have a webpage with a URL linking to a PHP file that displays an image, and I want to open this picture in a new window without the blank page showing up. Currently, when I click on the URL using the code below, a new window o ...

Is it possible that images appear normal locally, but become stretched once deployed? (CSS/HTML only)

I designed a straightforward webpage using only HTML and CSS. Everything looks great when I view it on my local machine. However, once I deployed the site on Droppages, a static-page hosting service integrated with Dropbox, all my images became stretched ...

What method was used to incorporate a 2 pixel margin between the th elements on this website?

I've been analyzing the code thoroughly, but I am still unable to decipher how they managed to create a 2px margin between the th elements: The website in question is: Does anyone have any insights on this? ...

Instructions for invoking an extra npm start script within Angular 2 cli configuration

Currently working on two different projects: Main angular 2 project which is launched using the cli/ng serve and runs on localhost:4200. Also working on Reveal.js, started using npm start and runs on localhost:8000 I'm interested in a way to stream ...