How to dynamically change styleUrls or style in Angular?

Viewed 22

I want to allow users to customize colors and some styles in Angular application. For that I want to make something 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

  }
}

How I can achieve that? I want to have some css files for every component and depend on user id I want to assign them to styleUrls. Someone can tell me how to do it?

1 Answers

You can use scss and wrap every stylesheet in a different class then based on the user’s selection change the class of your body.

Something like:

Style1.scss

.style1{
   your first css here…
}

Style2.scss

.style2{
   your second css here…
}

Adding/Removing class to/from body:

constructor(private renderer: Renderer2) {}

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

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

Related