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

前端 未结 2 578
余生分开走
余生分开走 2021-01-14 13:56

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

@Component({
  selector: \'open-account\',
  styleUrls: [\'open-account.component.scss\'         


        
相关标签:
2条回答
  • 2021-01-14 14:20

    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();
    }
    
    0 讨论(0)
  • 2021-01-14 14:21
     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');
        }
    }
    
    0 讨论(0)
提交回复
热议问题