将值绑定到样式

我试图从我的类(通过属性绑定获得)绑定一个颜色属性来设置 divbackground-color

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 + ";";
}
}

我的模板:

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

这个组件的用法:

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

我的绑定无法工作,但也不会抛出任何异常。

如果我将 {{changeBackground()}}放在模板中的某个位置,那么就会返回正确的字符串。

那么为什么样式绑定不能工作呢?

另外,我如何观察 Circle类中颜色属性的变化

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

角度2?

129555 次浏览

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>

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

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>
  • 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".

This works fine in Angular 11 and possibly earlier:

<div [style.backgroundColor]="myBgColor" [style.color]="myColor">Jesus loves you</div>

And in controller .ts file:

myBgColor = '#1A1A1A'
myColor = '#FFFFFF'