Dynamically updating css in Angular 2

tt9 picture tt9 · Mar 9, 2016 · Viewed 188.2k times · Source

Let's say I have an Angular2 Component

//home.component.ts

import { Component } from 'angular2/core';

@Component({
    selector: "home",
    templateUrl: "app/components/templates/home.component.html",
    styleUrls: ["app/components/styles/home.component.css"]
})
export class HomeComponent {
    public width: Number;
    public height: Number;
} 

The template html file for this component

//home.component.html

<div class="home-component">Some stuff in this div</div>

And finally the css file for this component

//home.component.css

.home-component{
    background-color: red;
    width: 50px;
    height: 50px;
}

As you can see there are 2 properties in the class, width and height. I would like the css styles for width and height to match the values of the width and height properties and when the properties update, the width and height of the div update. What is the proper way to accomplish this?

Answer

Gaurav Mukherjee picture Gaurav Mukherjee · Mar 9, 2016

Try this

 <div class="home-component" 
 [style.width.px]="width" 
 [style.height.px]="height">Some stuff in this div</div>

[Updated]: To set in % use

[style.height.%]="height">Some stuff in this div</div>