Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply styles to a component programatically angular 2?

I have a component with four different possible styles files that could be applied depending on some variable. How could I apply the styles of that component before it renders?

@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

     } 
   }


}
like image 848
raven Avatar asked Mar 29 '17 13:03

raven


2 Answers

Styles are compiled by Angular and with AoT this is done before you deploy the app, therefore there is nothing you can do at runtime. Without AoT this might work but I don't know about that.

One way would be to just add them all and switch between them using selectors

:host(.style1) {
  ...
}

:host(.style1) {
  ...
}
class MyComponent {
  style:string = 'style2';
  @HostBinding('class.style1') style1:boolean = style == 'style1';
  @HostBinding('class.style2') style2:boolean = style == 'style2';
}
like image 109
Günter Zöchbauer Avatar answered Nov 06 '22 05:11

Günter Zöchbauer


Günter is right. Here's a Plunker that implements such a strategy: https://plnkr.co/edit/LfjCS6DMSi8d44O4Uhkj?p=preview

I actually wrote a blog post on dynamically styling components and just noticed I missed this possibility. Gonna add it.

If you don't have the necessity to scope it to a single component, but if it's rather a "global" theming story, you could also take a look at handling this at a CSS level. Like having for instance a CSS class card which in style1.css is styled one way and in style2.css in the other.

I'd also try to look into the Angular Material 2 repo. They also talk about theming on the official site.

like image 3
Juri Avatar answered Nov 06 '22 07:11

Juri