首页 文章

Angular 2.0绑定到样式的值

提问于
浏览
71

我正在尝试绑定我的类中的颜色属性(通过属性绑定获取)来设置我的div的 background-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 + ";";
    }
}

My template:

<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类中color属性的变化?什么是替代品

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

角度2.0?

5 回答

  • 0

    原来样式绑定到字符串不起作用 . 解决方案是绑定样式的背景 .

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

    截至目前(2017年1月/ Angular> 2.0),您可以使用以下内容:

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

    <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>
    
  • 92

    我设法让它与alpha28一起工作:

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

    并称之为 <circle color='yellow'></circle>

  • 38

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

  • 17
    • app.component.html 使用中:
    [ngStyle]="{'background':backcolor}"
    
    • app.ts 中声明字符串类型 backcolor:string 的变量 .

    • 设置变量 this.backcolor="red" .

相关问题