Injecting styles dynamically into an Angular component enhances its appearance and functionality

I am in need of help with styling a component using CSS styles specified by an object of selectors to CSS properties. Check out my sandbox here: https://codesandbox.io/s/happy-goldberg-4740z

Here are the styles to be applied from the parent:

const styles = {
  a: [
    ['color', 'red']
  ],
  b: [
    ['color', 'blue']
  ]
};

Now, let's take a look at the component that needs to be styled dynamically:

@Component({
  selector: 'test',
  template: `
    <div>
      <span class="a">I am A</span>
      <span class="b">I am B</span>
    </div>
  `
})
export class Test implements OnInit {
  @Input() stylesToApply: { [key: string]: string[][] };

  constructor(private _renderer: Renderer2, private _element: ElementRef) {}

  ngOnInit() {
    let styleText = '';
    Object.entries(this.stylesToApply).forEach(([key, value]) => {
        const selector = `:host ${ key }`;
        let propStr = '';
        for (let i = 0; i < value.length; i++) {
            propStr += `${ value[i][0] }: ${ value[i][1] };\n`;
        }

        styleText += `${ selector} { ${ propStr } }\n`;
    });

    const styleElement = this._renderer.createElement('style');
    this._renderer.appendChild(styleElement, this._renderer.createText(styleText));
    this._renderer.appendChild(this._elementRef.nativeElement, styleElement);
  }
}

Although the result should be a <style> element injected into Test as shown below, I'm facing issues where the styles are not being properly applied:

<style>
:host a { color: red; }
:host b { color: blue; }
</style>

Answer №1

If you're looking to customize the style of an element in Angular, the official documentation provides a helpful guide on how to get started here

Start by creating an object that includes CSSStyleDeclaration properties. For example:

customStyle: CSSStyleDeclaration = { width: '100px', minHeight: '200px', backgroundColor: 'red' }

Then, within your component, you can apply the styles like this:

<div [style]="customStyle"></div>

This method allows you to easily pass styles directly to the element.

Alternatively, you could use @HostBinding, but that may not be the best solution for your specific needs.

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

Implement the Show/Hide TinyMCE Functionality in your <textarea></textarea> Box

Information I recently added TinyMCE to my website after discovering that a website I frequently visit uses it. While their design and functionality are different, I managed to replicate their look on my own site and now want to implement a specific featu ...

Unable to achieve the desired focus on a specific element using JavaScript's .focus() method

After executing the command $('#someelement').focus(), I am not receiving any error message but the functionality is not working as expected. Even when I attempt to retrieve document.activeElement, it continues to return the body element. Here i ...

Tips for avoiding accidental unit conversion in jQuery

Imagine having the following code: var $element = $('<div/>'); $element.css("margin-left", "2cm"); console.log($element.css("margin-left")); When tested in Chrome, it doesn't return anything, but Firefox shows "75.5833px". Any sugges ...

Encountering the "test exited without ending" error while using asynchronous forEach loops with tape

My Current Project Edit: I created a repository with a simplified version of the issue I am facing. Currently, my focus is on setting up automated frontend testing using tools like browserstack, selenium-webdriver, and tape. More information about tape ...

Encountering an issue with Apollo Express GraphQL: Error message stating that the schema must have distinct type names, yet it contains more than one type named "DateTime"

After importing the applyMiddleware library from 'graphql-middleware' to add validation middleware on mutation's input, I created a sample middleware function that logs the input. export const logInput = async (resolve, root, args, context, ...

What is the best approach to retrieve a JSON object from a form exception that has a specific name?

I have a certain form with input fields. My goal is to generate a JSON object from the form, excluding any input whose name is "point". However, my code doesn't seem to be working properly when I use the "not()" function. What am I doing wrong and how ...

Attempting to make a slightly bigger than usual AXIOS.post request to a .NET Web API

When attempting to perform an AXIOS.post in a Vue.JS application, the process fails when exceeding about 1500 characters. Instead of reaching the Web API, it goes directly to the error area. Typically, this function calls a .Net Web API that generates a MS ...

A React child error has occurred in Next.js due to invalid objects being used

Within my project, I have integrated the latest version of next.js and encountered an issue where objects are not valid as a React.js child. https://i.stack.imgur.com/MCO7z.png The problem arises after importing the Head component from Next.js and implem ...

Issues with Form Submission in Ionic 3

As a newcomer to Ionic 3 and Angular, I have been working on a login form with form validation in Ionic based on tutorials from Google. Despite following their instructions step by step, I am unable to get my form submitted. I am having trouble pinpointing ...

What is the method for exporting a default element from within the script setup block in Vue 3?

It appears that the export default statement is not functioning properly within <script setup>. For example, exporting it in a file called test.vue: <template> <div id="test" class="test"> </div> </templ ...

When reducing the page size, the Bootstrap columns are colliding with

While resizing the screen, I noticed that these images are overlapping each other. I haven't made any changes to the css for container-fluid or row. <div class="container-fluid bg-grey"> <div class="row center"> <div class= ...

Blogger website experiencing issue with Slick slider not automatically playing

I recently downloaded and customized the Slick Slider from the Slick Slider website and got it working perfectly on my local machine. However, when I added it to a blog website on blogger.com, I noticed that the auto play feature was not working and the n ...

The PHP query statement is encountering an unspecified parameter

I've been working on code to update a single entry in a SQL database, specifically targeting the invoice ID number ($num). However, I seem to be passing it incorrectly as my console is showing an Undefined value for the idinvoice. Interestingly, now ...

Change json data with multiple dimensions into an array using JavaScript

I have been attempting to retrieve each member by converting a multidimensional JSON stored in longtext format within MySQL to an array in JavaScript, but unfortunately, my attempts have not been successful. Here is the approach I have taken: Firstly, I ...

Embed Vue applications within the container of the main Vue application

My goal is to establish a foundational Vue application that offers essential features such as signing in, navigating with a sidebar, and the flexibility to interchange navbar items. I envision creating separate Vue applications for each navbar item. Main ...

Advantages of opting for Backbone instead of a jQuery plugin in this particular scenario

Seeking to compare the advantages of utilizing Backbone versus a jQuery Plugin in this specific case: There are 5 main sections within my application that users navigate between. Authentication and access to the application (all sections) is done through ...

Custom JavaScript files are not recognized by Angular 4 pages unless the page is manually refreshed

I am facing an issue with my custom JavaScript files in Angular. I have imported them all in the angular-cli.json file but the pages do not recognize them unless I refresh the page after navigating from one page to another. Here is a snippet of my angular ...

What is the most effective way to add images to a table using JavaScript?

Is there a way to insert images into the "choicesDiv" without having to make changes to the HTML & CSS? Here is the table code: <table id="choices"> <tr> <td><div class="choicesDiv" value="1"></div></td> ...

Angular code causing an unexpected blank page to be printed again

Trying to display the content of my HTML page is proving to be a challenge. I've been utilizing angularPrint, but an issue persists in the form of a second blank page appearing in the preview alongside the actual content. Eliminating this unwanted sec ...

Steps for setting a background image behind radio buttons

I am currently facing a challenge in adding a background image to a div that contains some radio buttons and updating it dynamically with Angular based on the current page. app.controller('thingCtrl', function ($scope, $rootScope, $routeParams ...