In Angular, you can add a unique design to an HTMLElement by applying a

I'm currently facing an issue with Typescript where I am attempting to apply a style on a HTMLElement. Below is the code snippet:

 styleChoice(element:HTMLElement){
    console.log(element);
    element.style.background="rgba(228, 48, 48, 0.2)";
    element.style.borderRadius="40px";
  
  }
  test(){
    console.log(document.getElementById('test'));
    this.styleChoice(document.getElementById('test'));
   
  }

Unfortunately, I am unable to figure out why it's not working as expected.

Answer №1

To achieve this functionality, it is recommended to utilize the Renderer2 in your Angular application. Avoid direct manipulation of the document within your code. For more information, refer to this resource.

export class DemoComponent {
  constructor(
    private element: ElementRef,
    private renderer: Renderer2,
  ){

  }

styleChoice(element:HTMLElement){
    console.log(element);
    //element.style.background="rgba(228, 48, 48, 0.2)";
    renderer.setStyle(el, 'background', 'red');
    renderer.setStyle(el, 'borderRadius', '40px');
   // element.style.borderRadius="40px";
  
  }
  test(){
    console.log(document.getElementById('test'));
    this.styleChoice(document.getElementById('test'));
   
  }
}

For detailed information on using Renderer2, visit this link.

Answer №2

An alternative approach to achieving the desired result in Angular is by utilizing a variable and [ngStyle]

For example:

//in .ts
style={
   "background":"rgba(228, 48, 48, 0.2)",
   "borderRadius":"40px"
}
//in .html
<some-element [ngStyle]="style">...</some-element>

//or directly
 <some-element [ngStyle]="{'background':'rgba(228, 48, 48, 0.2)',
                                        'borderRadius':'40px'}">
     ...
 </some-element>

You can dynamically adjust the style based on a variable like this:

variable=true;
<some-element [ngStyle]="variable?style:null">...</some-element>

If you only need to modify one property, you can use [style.property]

//in .ts
backgroundColor="rgba(228, 48, 48, 0.2)"
//in .html
<some-element [style.background]="backgroundColor">...</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

Displaying decimal values in Angular as percentages

In my Angular application, I have a numeric textbox that displays a percentage value and allows users to update it. https://i.stack.imgur.com/eCOKe.png <label for="fees">Fees %</label> <div class="inpu ...

Reposition the span element to the right of the div tag

I need help adjusting the positioning of the elements in this HTML code. How can I move the span element with the image to the right of the div tag? Here is the code snippet: <div style='width:600px;padding-top: 2px;padding-bottom: 1px'& ...

Experimenting with error boundaries by utilizing the React Testing Library and Jest:

I am facing an issue while writing a test for my error boundary higher-order component (HOC). The problem arises when I mock throwing an error in my wrapped component, causing the test to fail because it recognizes the error as a genuine one instead of und ...

What causes a neighboring div to change width when a multi-line span is present?

Here is my React code: <InfoWrapper> <InfoCircle> <span>i</span> </InfoCircle> <span className="info-label"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. elit. </span> </InfoWrap ...

Embedding Custom CSS Within a Parent CSS Element

After implementing a Wordpress Theme, I encountered the need to customize the styles of one of its elements. (This particular element displays our tours automatically) Currently, the style is as follows: .tourmaster-tour-grid .tourmaster-tour-content-wrap ...

Step-by-step guide on importing `block-ui`, `spectrum-colorpicker`, and `sass.js` libraries in a TypeScript project

I have been utilizing various plugins such as block-ui, spectrum-colorpicker, sass.js, etc., in my Angular 2 project written in TypeScript. Currently, I am loading these plugins directly in the index.html file. However, I would like to import them and onl ...

Why is the `node-config` configuration undefined within a TypeScript Jest environment?

I have a TypeScript module that is functional in both development and production environments. It utilizes https://github.com/lorenwest/node-config. When I attempt to import it into Jest for testing purposes, I encounter an error suggesting that the config ...

Error encountered while attempting to obtain OAuth2 API authorization token in ExpressJS Node.js Angular: "getaddrinfo ENOTFOUND"

Recently, I developed an angular application that sends an HTTP post request to a Node/Express.js endpoint upon clicking a button in order to obtain an authorisation token. I successfully configured the necessary credentials for basic OAuth2 authorisation ...

HTML Brickwork Picture Arrangement

I recently integrated this code into a WordPress theme and encountered an issue where the new images are displaying vertically instead of horizontally. I am seeking assistance in aligning the new images to appear on the green line instead of the red line a ...

Creating a dynamic website with user-friendly editing capabilities

Having a good understanding of html5 and css3, I am currently exploring ways to create a website that enables visitors to edit content in real time for all other users to see. While aware of the contenteditable attribute, I have found that it does not reta ...

Transforming button alignment from vertical to horizontal in Bootstrap based on the screen size of the device

My website features a series of vertically aligned buttons on the sidebar, styled using the following CSS: CSS: .sidebar { position: fixed; left: 20px; top: 5%; width: 120px;} .sidebar .icons { font-size: 30px; margin: 21px; } ...

Astro encounters issues with importing MD files when built, but functions properly when running npm dev

Currently, I am facing an issue with importing MD files in Astro and I am using the following code snippet: import * as a from '../content/a.md'; While this code works perfectly fine when running "npm run dev", it throws an error during the buil ...

Guide to implementing a real-time countdown timer for days, hours, minutes, and seconds leading up to a specific date and time with JavaScript

Implement a dynamic countdown timer in JavaScript that counts up to a specific date. See the example image for reference: here ...

Angular 7 and Spring 5 are being hindered by CORS restrictions

I'm currently working on a project that involves Spring 5 with Spring Security and Angular 7. I am facing an issue while trying to connect the frontend, receiving the following error message. It's worth mentioning that the backend and frontend pr ...

Customizing Bootstrap Navbar: Ensuring the External Search Bar is displayed correctly within the expanded navbar

In my Bootstrap 5 navbar, I have a search bar, notifications dropdown, and collapsible buttons. How can I ensure that the search bar is visible in the expanded version of the navbar and hidden when the navbar is collapsed, while keeping the notifications d ...

Interacting between components using Angular 2 services

I am attempting to implement bidirectional service communication using Angular. I have followed the instructions provided in the documentation here: https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service interactio ...

Ensuring IconButton is perfectly aligned with Text in one straight line

I want to display IconButtons alongside plain text in a single block of text, but the result didn't turn out as I had hoped. Here is what I attempted: JS(ReactJS): <div> <span> <h3>Title</h3> <IconButton className ...

Creating a Personalized Dropdown Menu Within the <div> Tag

My current task involves obtaining an element in the following format: https://i.sstatic.net/uhHkL.png Inside the nav-item, there is a dropdown with a top-centered triangle on it, and the dropdown is positioned at the center. Below is what I have achiev ...

Unable to view sidebar navigation on the screen

I've been experimenting with the sidebar navigation from w3 schools, specifically trying to create a side-nav that opens from one div. You can see an example here: http://www.w3schools.com/w3css/tryit.aspfilename=tryw3css_sidenav_left_right&stack ...

Integrating blade code within blade code

Struggling to craft a button using the Form builder. {!! Form::button('<span style="color: {!! $colour[$i] !!}" class..') !!} The specific details of the button don't matter, all I wanted was to adjust the font color to $colour[$id]. Th ...