What is the best way to dynamically update styleUrls or style properties in Angular?

One of my goals is to give users the ability to customize colors and certain styles within my Angular application. I am thinking about creating a structure like this:

Structure:

component-one
  folder-with-css-files
    style-for-component-1-for-client1.css
    style-for-component-1-for-client2.css
    style-for-component-1-for-client3.css
    style-for-component-1-for-client4.css

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.style-for-component-1-for-client{clientId}.css'],
})
export class AppComponent implements OnInit {

  clientId: string;

  ngOnInit(): void {
    // pseudocode
    clientId = service.fetchClientId() // for example

  }
}

I'm wondering how I can make this happen. My plan is to have specific css files for each component and assign them dynamically based on the user's id. Is there anyone who can guide me through the process?

Answer №1

To implement different styles based on user selection, you can utilize scss and encapsulate each stylesheet within a unique class. Then, dynamically change the class of the body element according to the user's preference.

Here is an example:

DarkMode.scss

.darkMode{
   /* add your dark mode CSS here */
}

LightMode.scss

.lightMode{
   /* add your light mode CSS here */
}

In your index.html file:

<body class="lightMode"></body>

By default, the light mode styling will be applied. If you replace the body classes with 'darkMode' in any component, the dark mode styling will take effect.

Add/Remove classes to/from the body tag dynamically:

constructor(private renderer: Renderer2) {}

addClass(){
    this.renderer.addClass(document.body, 'className');
}

removeClass(){
    this.renderer.removeClass(document.body, 'className');
}

You can also add/remove classes within components by using a wrapping div with a specific class:

component.html:

<div [class]="className">
    <!-- your HTML content goes here... -->
</div>

component.scss:

.greenDefault{
   /* green default CSS here */
}

.redDefault{
   /* red default CSS here */
}

.greyDefault{
  /* grey default CSS here */
}

component.ts

className: string;

changeStyle(class: string){
   this.className = class;
}

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

Tips for enabling scrolling on mobile devices

Hello there, I'm facing an issue with scrolling on my website when viewed on mobile devices. Even though I have set the div height to 100%, it appears as 'auto' on mobile screens. As a result, when the text exceeds the screen height, it bec ...

Incorporate a style sheet for a colorful navigation bar

I'm looking to add a colored bar below my navigation menu but I'm unsure of the correct method to do so. What I need: EDIT: I also need guidance on how to position the navigation menu at 50% of the height of the logo. Currently, I have used a & ...

CSS - Mysterious Gaps Found in Div Block

Below is the code snippet I am currently working with: html { height: 100%; overflow: hidden; } body { height: 100%; color: #bdc3c7; font-family: Montserrat; background-color: #3E4651; } .nav { ...

Is Angular4 preloaded with bootstrap library?

I started a new angular4 project and wrote the code in app.component.html <div class="container"> <div class="row"> <div class="col-md-1">.col-md-1</div> <div class="col-md-1">.col-md-1</div> <div class ...

Ensure that grid rows occupy the least amount of space possible

I'm relatively new to grid layout and I've encountered a challenge that has me stuck. Here's what I have so far: codepen And this is the relevant part of the grid: grid-template: 'img date' 'img head' 'img s ...

What is the recommended approach for storing and retrieving images in the Angular 5 framework?

I have an Angular 5 app that utilizes Java rest services. The Java application stores images in a folder located outside of the Java app itself. Now, my goal is for the Angular app to be able to read these images. Although it makes sense to store them outs ...

Unusual CSS inconsistencies between running on VS Web Server and IIS

My current dilemma involves a discrepancy in the appearance of my site when viewed locally through the visual studio web server (http://localhost:3452/) compared to when accessed on IIS7 (http://server/myproject/). Initially, I suspected a CSS issue causi ...

The presence of a Bootstrap addon is resulting in horizontal scrolling on mobile devices within the webpage

I am encountering a peculiar issue with an input-group in my cshtml file which features a Bootstrap addon. The problem arises on mobile devices, where upon focusing on the input field, the page scrolls horizontally to the right, revealing the right margin ...

What is a CSS drop-down menu/container?

I've been brainstorming a unique dropdown menu style that involves dropping down a container, but I'm a bit stuck on how to execute it effectively. Although I've outlined the basic concept, I'm still unsure of the implementation. Any t ...

Using the arrow keys to navigate through a list of items without using jQuery

Exploring ways to develop a basic autocomplete feature without relying on third-party dependencies has been my recent project. So far, I have managed to populate a results list using an ajax call and complete fields with mouse onclick events for each optio ...

ViewContainerRef fails to render component on the DOM

@Component({ selector: 'my-cmp', template: ` <div #target></div> ` }) export class MyCmp { @ViewChild('target', {read: ViewContainerRef}) target : ViewContainerRef; render() { let component = createComponent(met ...

What is the best way to access dependencies that are externally defined in the root package.json file?

I'm unsure of the appropriate terminology for this concept. If you have the correct TERM to share or a reference for me to learn more about it, please provide the link. Currently, I am examining our extensive package.json file for various projects. ...

Modify the appearance of the post-content's color and background when hovering

I am struggling to achieve the goal of changing the background of the search box to transparent and making the search icon white on hover. Any help or suggestions would be greatly appreciated! Below is the code where I want to apply the hover CSS effect: ...

Looking to center the numbers in my ordered list within a border box - any tips on how to achieve this?

I'm attempting to create a numbered order list with a circular border around it. The goal is to have the number of the list item centered within the circular border and the entire circle centered within the paragraph. Currently, both the number and th ...

Importing the Ivy library component in Angular by specifying the module path as a string

Currently, I'm working with the latest Ivy release candidate. Scenario: I need to make multiple modules available for separate compilation and runtime loading using import statements, without relying on loadChildren from the router module. Backgroun ...

Modifying ngModel will result in the corresponding ngModel in another Angular2 browser being updated

I'm a novice when it comes to Angular 2 and I'm currently working on a project using npm to run the application. At the moment, I have it hosted on localhost with port 3000. The issue I'm facing in my project is that when I open the same ...

Reset Angular Material autocomplete upon selection

The issue I'm encountering is as follows: when an option is chosen from the autocomplete input, it should not only add a chip to the Angular Material Chips component (which it currently does), but also clear the autocomplete input so that another opti ...

The struggle continues in attempting to adjust Angular Material 2 dialog positioning using MdDialogConfig

Does anyone know how to adjust the position of an MdDialog? openDialog() { let config = new MdDialogConfig(); config.height = '15px'; config.position.left = '5px'; let dialogRef = this.dialog.open(BasicAlertDialog, config); dialogRef. ...

Potential solution for communication issue between Angular CLI and Flask due to cross-origin error

Initially, the user id and password are submitted from the UI (angular) to Flask: public send_login(user){ console.log(user) return this.http.post(this.apiURL+'/login',JSON.stringify(user),this.httpOptions) .pip ...

"Combining background images with javascript can result in displaying visual elements

Hello! I am in need of assistance with a CSS + Javascript fog effect that I have developed. It is functioning properly on Firefox, Opera, and Chrome but encountering issues on IE and Edge browsers. The effect involves moving two background images within a ...