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

强颜欢笑 提交于 2019-12-01 21:52:43

问题


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.


回答1:


 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');
    }
}



回答2:


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();
}


来源:https://stackoverflow.com/questions/42496999/angular-2-how-do-i-conditionally-add-styles-to-my-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!