Search code examples
angularangular12

Angular change the styleUrls value from inside the component


I am trying the allow the user the change the styleUrls value at runtime, so Im trying this:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  // styleUrls: [ './app.component.css' ]
  styleUrls: [styleUrl]

})
export class AppComponent implements OnInit  {

  styleUrl = './app.component.css'
  
  ngOnInit() {

    this.styleUrl = './another.css';

  }

}

This does not work so is it possible to get something like this to work?

If so how?


Solution

  • It doesn't work that way. Here is a simple example with two css files and ngClass

    Here were are making the component light / dark according to user interaction.

    styleUrls: ['./app.component.light.css', './app.component.dark.css']
    

    stylesheet - light(app.component.light.css)

    .light.highlight {
        color: #fff;
        background-color: #000;
    }
    

    stylesheet - dark(app.component.dark.css)

    .dark.highlight {
        color: #000;
        background-color: #fff;
    }
    

    Now create a base wrapper div for the whole component

    <div [ngClass]="isLight ? 'light': 'dark'">
        <!--component content goes here-->
    </giv>
    

    If you use scss instead, you can use a wrapper just like you used in html

    .light {
        // page styles go here
    }