georgej
georgej

Reputation: 3311

Angular 2 - How do I conditionally add styles to my component?

I have a component with a stylesheet that loads correctly like this:

@Component({
  selector: 'open-account',
  styleUrls: ['open-account.component.scss'],
  templateUrl: './open-account.component.html',
})

I want to conditionally load another stylesheet if the string widget=true is present in the url but cannot get anyway to work. I have tried:

var stylesArr = ['open-account.component.scss'];
if (window.location.href.indexOf('widget=true') > -1) stylesArr.push('open-account-widget-styles.component.scss');

@Component({
  selector: 'open-account',
  styleUrls: stylesArr,
  templateUrl: './open-account.component.html',
})

and

var stylesArr = ['./open-account.component.scss'];
if (window.location.href.indexOf('widget=true') > -1) stylesArr.push('./open-account-widget-styles.component.scss');

@Component({
  selector: 'open-account',
  styleUrls: stylesArr,
  templateUrl: './open-account.component.html',
})

and

@Component({
  selector: 'open-account',
  styleUrls: ['open-account.component.scss', 'open-account-widget-styles.component.scss'].filter(elem => {
    if (elem === 'open-account.component.scss') return true;
    if (elem === 'open-account-widget-styles.component.scss' && window.location.href.indexOf('widget=true') > -1) return true;
  }),
  templateUrl: './open-account.component.html',
})

and in at the top of my html:

<style type="text/css" *ngIf="false">
(the 'false' would be a variable, but putting in false doesnt even stop the style from loading)
...
</style>

What can I do to conditionally load an additional stylesheet like this? Im not sure what else to try.

Upvotes: 4

Views: 4602

Answers (2)

georgej
georgej

Reputation: 3311

The only way I found it works is to do this:

addStyleSheet() {
  var headID = document.getElementsByTagName('head')[0];
  var link = document.createElement('link');
  link.type = 'text/css';
  link.rel = 'stylesheet';
  link.id = 'widget_styles';
  headID.appendChild(link);

  link.href = './app/open-account/open-account-widget-styles.component.css';
}

ngOnInit() {
  this.addStyleSheet();
}

Upvotes: 1

Yoav Schniederman
Yoav Schniederman

Reputation: 5391

 import { Component, Inject } from '@angular/core';
 import { DOCUMENT } from '@angular/platform-browser';

 @Component({
 })

 export class SomeComponent {

    constructor (@Inject(DOCUMENT) private document) { }

        LightTheme() {
            this.document.getElementById('theme').setAttribute('href', 'light-theme.css');


        DarkTheme() {
            this.document.getElementById('theme').setAttribute('href', 'dark-theme.css');
    }
}

Upvotes: 0

Related Questions