user2313300 user2313300 - 6 months ago 54
CSS Question

Dynamically updating css in Angular 2

Let's say I have an Angular2 Component


import { Component } from 'angular2/core';

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


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

And finally the css file for this component


background-color: red;
width: 50px;
height: 50px;

As you can see there are 2 properties in the class,
. 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?


This should do it:

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