Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 364
georgej Avatar asked Nov 21 '25 07:11

georgej


1 Answers

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();
}
like image 85
georgej Avatar answered Nov 23 '25 03:11

georgej