动态styleUrls在angular 2? [英] Dynamic styleUrls in angular 2?

查看:914
本文介绍了动态styleUrls在angular 2?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以动态地将样式表的网址插入到组件中?

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

类似:

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

或者(假想并注意这只是假的代码):

or (wishful thinking and note that this is just fake code):

export class MyComponent implements dynamicUrls {

  ngDynamicUrls() {
    this.inject(['anotherStylesheet.css', 'anotherStylesheet2.css']);
  }
}

因为如果你要能够样式从 stylesheet1 无需访问它,你应该怎么做?我唯一的想法是有动态 styleUrls 不知何故,但我不认为这是可能的,从我可以找到。

Because if you're gonna be able to override certain styles from stylesheet1 without having access to it, how are you supposed to do that? My only idea is to have dynamic styleUrls somehow but I don't think this is even possible from what I could find.

有什么想法吗?

推荐答案

你可以操作Angular 2组件装饰器,创建你自己的并返回Angular的装饰器与你的属性。

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



在你的组件中,用新的替换默认角度2 @Component。 p>

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 ......

这篇关于动态styleUrls在angular 2?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆