user2313300 user2313300 - 8 days ago 6
CSS Question

Dynamically updating css in Angular 2

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

This should do it:

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