Angular2 Dynamic Change CSS Property
Answer :
1) Using inline styles
<div [style.color]="myDynamicColor">
2) Use multiple CSS classes mapping to what you want and switch classes like:
/* CSS */ .theme { /* any shared styles */ } .theme.blue { color: blue; } .theme.red { color: red; } /* Template */ <div class="theme" [ngClass]="{blue: isBlue, red: isRed}"> <div class="theme" [class.blue]="isBlue">
Code samples from: https://angular.io/cheatsheet
More info on ngClass directive : https://angular.io/docs/ts/latest/api/common/index/NgClass-directive.html
Just use standard CSS variables:
Your global css (eg: styles.css)
body { --my-var: #000 }
In your component's css or whatever it is:
span { color: var(--my-var) }
Then you can change the value of the variable directly with TS/JS by setting inline style to html element:
document.querySelector("body").style.cssText = "--my-var: #000";
Otherwise you can use jQuery for it:
$("body").css("--my-var", "#fff");
You don't have any example code but I assume you want to do something like this?
@View({ directives: [NgClass], styles: [` .${TodoModel.COMPLETED} { text-decoration: line-through; } .${TodoModel.STARTED} { color: green; } `], template: `<div> <span [ng-class]="todo.status" >{{todo.title}}</span> <button (click)="todo.toggle()" >Toggle status</button> </div>` })
You assign ng-class
to a variable which is dynamic (a property of a model called TodoModel
as you can guess).
todo.toggle()
is changing the value of todo.status
and there for the class of the input is changing.
This is an example for class name but actually you could do the same think for css properties.
I hope this is what you meant.
This example is taken for the great egghead tutorial here.
Comments
Post a Comment