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
}
}
}
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';
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With