Dynamic styleUrls in angular 2?

后端 未结 5 1577
借酒劲吻你
借酒劲吻你 2020-11-30 07:50

Is it possible to dynamically inject urls to stylesheets into a component?

Something like:

styleUrls: [
  \'stylesheet1.css\',
  this.additionalUrls
         


        
5条回答
  •  甜味超标
    2020-11-30 07:59

    It's possible in some maybe hack way it worked for me. You can manipulate Angular 2 Component decorator, create your own and return Angular's decorator with your properties.

      import { Component } from '@angular/core';
    
        export interface IComponent {
          selector: string;
          template?: string;
          templateUrl?: string;
          styles?: string[];
          styleUrls?: string[];
          directives?: any;
          providers?: any;
          encapsulation?: number;
        }
    
        export function CustomComponent( properties: IComponent): Function {
          let aditionalStyles: string;
    
          try {
              aditionalStyles =  require(`path to aditional styles/${ properties.selector }/style/${        properties.selector }.${ GAME }.scss`);
              properties.styles.push(aditionalStyles);
            } catch (err) {
              console.warn(err)
            }
          }
    
          return Component( properties );
        }
    

    And in your component replace default angular 2 @Component with new one.

    import { CustomComponent } from 'path to CustomComponent';
    
    @CustomComponent({
      selector: 'home',
      templateUrl: './template/home.template.html',
      styleUrls: [ './style/home.style.scss']
    })
    export class ......
    

提交回复
热议问题