Angular 2.0绑定到样式的值
82049 观看
5回复
我正在尝试绑定我的类中的颜色属性(通过属性绑定获取)来设置background-color
我的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>
我的绑定不起作用,但也没有任何例外。如果我将{{changeBackground()}}
某个地方放在模板中,那确实会返回正确的字符串。那么为什么样式绑定不起作用?
还想到它,我如何观察Circle类中color属性的变化?什么是替代品
$scope.$watch("color", function(a,b,){});
角度2.0?
作者: user1613512 的来源 发布者: 2019 年 5 月 29 日回应 (5)
93像
原来样式绑定到字符串不起作用。解决方案是绑定样式的背景。
<div class="circle" [style.background]="color">
作者: user1613512
发布者: 08.04.2015 02:50
38像
截至目前(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>
最短的方式可能是这样的:
<div class="circle" [ngStyle]="{ 'background-color': color }">
<!-- <content></content> --> <!-- content is now deprecated -->
<ng-content><ng-content> <!-- Use ng-content instead -->
</div>
作者: andreas
发布者: 11.01.2017 01:01
16像
我设法让它与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>
1像
0像
在你的 app.component.html中使用:
[ngStyle]="{'background':backcolor}"
在app.ts中声明字符串类型的变量
backcolor:string
。设置变量
this.backcolor="red"
。
来自类别的问题 :
- angular 如何查看我使用的Angular版本?
- angular AngularJS:如何清除URL中的查询参数?
- angular angular:根据模型中的布尔值切换按钮文本
- angular Angular 2:是否强制使用括号/方括号?
- angular 在最新的TypeScript(大概是v1.5)示例中,@(符号)是什么意思?
- angular Angular 2.0绑定到样式的值
- angular Angular没有NameService的提供者
- angular 如何在Angular中使用jQuery?
- angular 如何使FileReader与Angular2一起使用?
- angular 如何在Angular 2中的组件之间共享数据?
- angular 如何在Angular2中订阅服务上的事件?
- angular Angular 2.0路由器无法重新加载浏览器
- angular 在Angular中迭代对象
- angular Angular HTML绑定
- angular Angular2验证器,它依赖于多个表单字段
- angular 具有多个视图的Angular 2组件
- angular 抓住Angular 2例外
- angular 角度和去抖动
- angular 如何禁用“提交”按钮?
- angular 有人知道如何在Angular2中触发Form Validators吗?