我正在尝试绑定我的类中的颜色属性(通过属性绑定获取)来设置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 + ";";
}
}
Run Code Online (Sandbox Code Playgroud)
我的模板:
<style>
.circle{
width:50px;
height: 50px;
background-color: lightgreen;
border-radius: 25px;
}
</style>
<div class="circle" [style]="changeBackground()">
<content></content>
</div>
Run Code Online (Sandbox Code Playgroud)
该组件的用法:
<circle color="teal"></circle>
Run Code Online (Sandbox Code Playgroud)
我的绑定不起作用,但也没有任何例外.如果我将{{changeBackground()}}某个地方放在模板中,那确实会返回正确的字符串.那么为什么样式绑定不起作用?
还想到它,我如何观察Circle类中color属性的变化?什么是替代品
$scope.$watch("color", function(a,b,){});
Run Code Online (Sandbox Code Playgroud)
角度2.0?
use*_*512 95
原来样式绑定到字符串不起作用.解决方案是绑定样式的背景.
<div class="circle" [style.background]="color">
Run Code Online (Sandbox Code Playgroud)
and*_*eas 38
截至目前(2017年1月/ Angular> 2.0),您可以使用以下内容:
changeBackground(): any {
return { 'background-color': this.color };
}
Run Code Online (Sandbox Code Playgroud)
和
<div class="circle" [ngStyle]="changeBackground()">
<!-- <content></content> --> <!-- content is now deprecated -->
<ng-content><ng-content> <!-- Use ng-content instead -->
</div>
Run Code Online (Sandbox Code Playgroud)
最短的方式可能是这样的:
<div class="circle" [ngStyle]="{ 'background-color': color }">
<!-- <content></content> --> <!-- content is now deprecated -->
<ng-content><ng-content> <!-- Use ng-content instead -->
</div>
Run Code Online (Sandbox Code Playgroud)
kak*_*aja 20
我设法让它与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;
}
}
Run Code Online (Sandbox Code Playgroud)
并称它为这样 <circle color='yellow'></circle>
这在 Angular 11 甚至更早的版本中工作得很好:
<div [style.backgroundColor]="myBgColor" [style.color]="myColor">Jesus loves you</div>
Run Code Online (Sandbox Code Playgroud)
在控制器 .ts 文件中:
myBgColor = '#1A1A1A'
myColor = '#FFFFFF'
Run Code Online (Sandbox Code Playgroud)
小智 5
在您的app.component.html 中使用:
[ngStyle]="{'background-color':backcolor}"
Run Code Online (Sandbox Code Playgroud)
在app.ts 中声明字符串类型的变量backcolor:string。
设置变量this.backcolor="red"。
| 归档时间: |
|
| 查看次数: |
90646 次 |
| 最近记录: |