How to add stylesheet dynamically in Angular 2?

Is there a way to add styles url or <style></style>

dynamically in Angular2?

For example, if my variable isModalOpened

is equal true

, I would like to add some CSS to multiple elements outside of my root component. Like body

or html

.

It can be done with DOM or jQuery, but I would like to do it with Angular 2.

Maybe?

thank

+3


source to share


3 answers


You can create a tag <style>

dynamically like this:



ngOnInit() {
  const css = 'a {color: pink;}';
  const head = document.getElementsByTagName('head')[0];
  const style = document.createElement('style');
  style.type = 'text/css';
  style.appendChild(document.createTextNode(css));
  head.appendChild(style);
}

      

+2


source


I'm not sure if you can do this in body or html, but you can do it using the root component.

  • Create a service nested in the root component
  • Let the service have a state (maybe BehaviorSubject

    )
  • Access to this service and change state when changing isModalOpened

  • In the root component, you will observe this and change the values โ€‹โ€‹of the component parameters
  • Inside the root html component you can change the class values โ€‹โ€‹based on the component parameter values

Update : Customize the background color from the inner component.

app.component.css

.red{
    background: red;
 }

.white{
    background: white;
 }
.green{
    background: green;
 }

      

app.component.html

<div  [ngClass]="backgroundColor" ></div>

      



app.component.ts

constructor(private statusService: StatusService) {
    this.subscription = this.statusService.getColor()
    .subscribe(color => { this.backgroundColor = color; });
}

      

status.service.ts

private color = new Subject<any>();
public setColor(newColor){
    this.color.next(newColor);
}
public getColor(){
    return this.color.asObservable();
}

      

child.component.ts

export class ChildComponent {
    constructor(private statusService: StatusService) {}

    setColor(color:string){
      this.statusService.setColor(color);
    }
}

      

So whenever we call setColor and pass in a color variable such as red, green, or white, the background of the root component changes accordingly.

0


source


Put all your html code in a custom directive - call ngstyle ...

Add your ngstyle to your page using directive tags, in our case:

<ngstyle><ngstyle>

      

but also add logic to your directive using ng - if you can enable or disable it ...

<ngstyle ng-if="!isModalOpened"><ngstyle>

      

Now if your 'isModalOpened' is set to your controller scope like this:

$scope.isModalOpened = false; //or true, depends on what you need

      

... you can toggle it true or false in a lot of different ways that should turn your directive on and off.

0


source







All Articles