将价值绑定到样式 [英] Binding value to style

查看:46
本文介绍了将价值绑定到样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从我的类中绑定一个颜色属性(通过属性绑定获取),以设置我的 div background-color .

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

我的模板:

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

我的绑定无法正常工作,但也不会引发任何异常.

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

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

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

那为什么样式绑定不起作用?

So why is the style binding not working?

此外,我将如何观察 Circle 类中color属性的更改?什么是

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,){});

在Angular 2中?

in Angular 2?

推荐答案

将样式绑定到字符串无效.解决方案是绑定样式的背景.

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

这篇关于将价值绑定到样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆