[angular] Binding value to style

I'm trying to bind a color property from my class (acquired by attribute binding) to set the background-color of my div.

import {Component, Template} from 'angular2/angular2';

@Component({
  selector: 'circle',
  bind:{
    "color":"color"
  }
})
@Template({
  url: System.baseURL + "/components/circle/template.html",
})
export class Circle {
    constructor(){

    }

    changeBackground():string{
        return "background-color:" + this.color + ";";
    }
}

My template:

<style>
    .circle{
        width:50px;
        height: 50px;
        background-color: lightgreen;
        border-radius: 25px;
    }
</style>
<div class="circle" [style]="changeBackground()">
    <content></content>
</div>

The usage of this component:

<circle color="teal"></circle>

My binding is not working, but doesn't throw any exceptions either.

If I would put {{changeBackground()}} somewhere in the template, that does return the correct string.

So why is the style binding not working?

Also, how would I watch the changes to the color property inside the Circle class? What is the replacement for

$scope.$watch("color", function(a,b,){});

in Angular 2?

This question is related to angular

The answer is


As of now (Jan 2017 / Angular > 2.0) you can use the following:

changeBackground(): any {
    return { 'background-color': this.color };
}

and

<div class="circle" [ngStyle]="changeBackground()">
    <!-- <content></content> --> <!-- content is now deprecated -->
    <ng-content><ng-content> <!-- Use ng-content instead -->
</div>

The shortest way is probably like this:

<div class="circle" [ngStyle]="{ 'background-color': color }">
    <!-- <content></content> --> <!-- content is now deprecated -->
    <ng-content><ng-content> <!-- Use ng-content instead -->
</div>

Try [attr.style]="changeBackground()"


  • In your app.component.html use:

      [ngStyle]="{'background-color':backcolor}"
    
  • In app.ts declare variable of string type backcolor:string.

  • Set the variable this.backcolor="red".


Turns out the binding of style to a string doesn't work. The solution would be to bind the background of the style.

 <div class="circle" [style.background]="color">

I managed to make it work with alpha28 like this:

import {Component, View} from 'angular2/angular2';

@Component({
  selector: 'circle', 
  properties: ['color: color'],
})
@View({
    template: `<style>
    .circle{
        width:50px;
        height: 50px;
        border-radius: 25px;
    }
</style>
<div class="circle" [style.background-color]="changeBackground()">
    <content></content>
</div>
`
})
export class Circle {
    color;

    constructor(){
    }

    changeBackground(): string {
        return this.color;
    }
}

and called it like this <circle color='yellow'></circle>