Angular2 is providing ngStyle to set CSS dynamically as like Angular1, but syntax is different. We can assign CSS element  by using JavaScript element.

Using ngStyle

Observe below highlighted code. [] represents one way binding
<button (click)="myStyle={color:'red'}">Set Color</button>
<button (click)="myStyle={'background-color':'blue'}">Set Background color</button>
<button (click)="myStyle = {}">clear</button>
<div [ngStyle]="myStyle">Click above button to set text color</div>
View DEMO

Using element style property

Observe below code. Here style.width was bound to myStyleWidth
<div [style.width.px]="myStyleWidth" [style.border]="myBorderStyle">
  sample text in div
</div>
Div Width :: <input [(ngModel)]="myStyleWidth"/>
border style :: <input [(ngModel)]="myBorderStyle"/>
View DEMO

0 comments:

Blogroll

Follow this blog by Email

Popular Posts