Steffi
Steffi

Reputation: 7057

How to add stylesheet dynamically in Angular 2?

Is there a way to add stylesheet url or <style></style> dynamically in Angular2 ?

For example, if my variable is isModalOpened is true, I would like to add some CSS to few elements outside my root component. Like the body or html.

It's possible to do it with the DOM or jQuery but I would like to do this with Angular 2.

Possible ?

Thanks

Upvotes: 6

Views: 3845

Answers (3)

ebrehault
ebrehault

Reputation: 2601

You can create a <style> tag 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);
}

Upvotes: 5

Vamshi
Vamshi

Reputation: 9331

I am not sure you can do it to body or html, but you can do it to root component.

  • Create a service injected to root component
  • Let the service have a state ( may be BehaviorSubject )
  • Access that service and change the state when isModalOpened is changed
  • In root component , you will be watching this and change component parameter values
  • Inside root component html , you can change class values based on the component param values

Update : Setting background color from an 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 a color variable such as 'red', 'green' or 'white' the background of root component changes accordingly.

Upvotes: 1

altShiftDev
altShiftDev

Reputation: 1632

Put all your html code in a custom directive - let's call it ngstyle...

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

<ngstyle><ngstyle>

but let's also append the logic to your directive using ng-if so you can toggle it on or off...

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

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

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

...you can toggle it true or false many different ways which should toggle your directive on and off.

Upvotes: 0

Related Questions