Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/backbone.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 将值绑定到样式_Angular - Fatal编程技术网

Angular 将值绑定到样式

Angular 将值绑定到样式,angular,Angular,我正在尝试从我的类绑定一个颜色属性(通过属性绑定获得),以设置我的div的背景颜色 从'angular2/angular2'导入{组件,模板}; @组成部分({ 选择器:'圆', 绑定:{ “颜色”:“颜色” } }) @模板({ url:System.baseURL+“/components/circle/template.html”, }) 出口阶级圈子{ 构造函数(){ } changeBackground():字符串{ 返回“背景色:“+this.color+”;”; } } 我的模板

我正在尝试从我的类绑定一个颜色属性(通过属性绑定获得),以设置我的
div
背景颜色

从'angular2/angular2'导入{组件,模板};
@组成部分({
选择器:'圆',
绑定:{
“颜色”:“颜色”
}
})
@模板({
url:System.baseURL+“/components/circle/template.html”,
})
出口阶级圈子{
构造函数(){
}
changeBackground():字符串{
返回“背景色:“+this.color+”;”;
}
}
我的模板:


.圆圈{
宽度:50px;
高度:50px;
背景颜色:浅绿色;
边界半径:25px;
}
此组件的用法:


我的绑定不起作用,但也不会抛出任何异常

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

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

另外,我如何查看
类中的color属性的更改?替代品是什么

$scope.$watch(“颜色”,函数(a,b,){});

在Angular 2中,将样式绑定到字符串是不起作用的。 解决方案是绑定样式的背景


我成功地使alpha28工作如下:

从'angular2/angular2'导入{组件,视图};
@组成部分({
选择器:'圆',
属性:['color:color'],
})
@看法({
模板:`
.圆圈{
宽度:50px;
高度:50px;
边界半径:25px;
}
`
})
出口阶级圈子{
颜色
构造函数(){
}
changeBackground():字符串{
返回此.color;
}
}
并这样称呼它

试试
[attr.style]=“changeBackground()”

从现在开始(2017年1月/Angular>2.0),您可以使用以下方法:

changeBackground():任意{
返回{'background color':this.color};
}


最短的路径可能是这样的:


  • 在你的app.component.html中使用:

      [ngStyle]="{'background-color':backcolor}"
    
  • app.ts中声明字符串类型的变量
    backcolor:string

  • 将变量设置为this.backcolor=“red”


这在Angular 11和更早的版本中可以正常工作:

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

为了清楚起见,您错过了自
起的引用:
颜色在本例中是组件上包含您要使用的值的属性。如果您使用的是引号,那么这就是您想要使用的值<代码>颜色
不是有效的CSS颜色。它需要类似于
[style.background]=“#f3'”
myBgColor = '#1A1A1A'
myColor = '#FFFFFF'