【问题标题】:How to apply styles to a component programatically angular 2?如何以编程方式将样式应用于组件 angular 2?
【发布时间】:2017-03-29 13:45:50
【问题描述】:

我有一个组件,其中包含四种不同的可能样式文件,可以根据某些变量应用这些样式文件。如何在渲染之前应用该组件的样式?

@Component({
    selector: 'settings-editor',
    templateUrl: './settings-editor.component.html',
    styleUrls: [ './a.less', './b.less' , './c.less' ]
})
export class SettingsEditorComponent implements OnInit {
   @Input()
   public styleType: string;


   ngOnInit() {
     if (this.styleType === 'A') { 
        // Apply styles  from a.less only

     } 
   }


}

【问题讨论】:

    标签: angular angular2-components


    【解决方案1】:

    君特是对的。这是一个实现这种策略的 Plunker:https://plnkr.co/edit/LfjCS6DMSi8d44O4Uhkj?p=preview

    我实际上是wrote a blog post on dynamically styling components,只是注意到我错过了这种可能性。会添加它。

    如果您没有必要将其限定为单个组件,但如果它是一个“全局”主题故事,您也可以考虑在 CSS 级别处理它。比如有一个 CSS 类 card,它在 style1.css 中是一种样式,而在 style2.css 中是另一种样式。

    我也会尝试查看Angular Material 2 repo。他们还谈论theming on the official site

    【讨论】:

      【解决方案2】:

      样式由 Angular 编译,而 AoT 是在您部署应用程序之前完成的,因此您在运行时无能为力。如果没有 AoT,这可能会起作用,但我不知道。

      一种方法是将它们全部添加并使用选择器在它们之间切换

      :host(.style1) {
        ...
      }
      
      :host(.style1) {
        ...
      }
      
      class MyComponent {
        style:string = 'style2';
        @HostBinding('class.style1') style1:boolean = style == 'style1';
        @HostBinding('class.style2') style2:boolean = style == 'style2';
      }
      

      【讨论】:

        猜你喜欢
        • 2019-02-23
        • 1970-01-01
        • 2018-05-15
        • 1970-01-01
        • 2012-12-04
        • 2016-11-13
        • 2017-03-27
        • 2016-04-16
        • 2019-02-14
        相关资源
        最近更新 更多