Angular 使用角度2样式绑定绑定rgb颜色值
我想把像“200,55100”这样的rgb值从后端绑定到div的背景色 这不起作用,它抛出模板解析异常Angular 使用角度2样式绑定绑定rgb颜色值,angular,angular2-template,Angular,Angular2 Template,我想把像“200,55100”这样的rgb值从后端绑定到div的背景色 这不起作用,它抛出模板解析异常 <div [style.background-color]="rgb({{model.color}})" X {{s.subjectName} 不能同时使用属性绑定([]语法)和插值({}}语法)。原因是Angular2在插值的幕后创建了一个属性绑定(另请参见) 我建议尝试以下插值方法: <div style.background-color="rgb({{model.colo
<div [style.background-color]="rgb({{model.color}})"
X
{{s.subjectName}
不能同时使用属性绑定([]语法)和插值({}}语法)。原因是Angular2在插值的幕后创建了一个属性绑定(另请参见)
我建议尝试以下插值方法:
<div style.background-color="rgb({{model.color}})">...</div>
我有一个类似的例子,需要像属性指令一样绑定客户端颜色转换 在我的例子中,我曾经需要这个功能,在Angular之前,我依靠jQuery将我在关键字中设置的颜色转换为RGB,以便在背景上自动对比文本。如果需要进行颜色转换,请查看npm上的颜色转换 如果您在
colorboutground()
和colorText()
中调整颜色转换,您应该能够执行相同的操作
带插值的rgb(…)之前是否应该有“:”?无论如何,这两种方法都不起作用。然后我也尝试了=>我需要s。因为这是我最喜欢的东西。也不起作用,因为s是未定义的。我的意思是:[style.background color]=“s.getColor()”>s是未定义的。我已经用我的HTML更新了我的问题。我不建议
…
。与其使用..
或..
@GünterZöchbauer多谢,我尝试了=>[style.background color]=“'rgb('+model.color+')””,效果不错!直接绑定到属性,如class
和style
在Safari(移动)上无法正常工作<应该改用code>ngStyle、ngClass
或[style.stylePropName]=…
。您能显示“s.getColor()”实现吗?它不能不再出现在我的代码中了:P
<div style.background-color="rgb({{model.color}})">...</div>
<div [style.background-color]="'rgb(' + model.color + ')'">...</div>
public getColorString(): string {
return 'rgb(200, 55, 100)';
}
import { Directive, ElementRef, Input } from '@angular/core';
var convert = require('color-convert');
@Directive({
selector: '[maAutoContrast]'
})
export class AutoContrastDirective {
@Input('bgColor')
// E.g. 'blue'
public bgColor: string;
constructor(private el: ElementRef) { }
public ngOnInit(): void {
this.colorBackground();
this.colorText();
}
private colorBackground(): void {
this.el.nativeElement.style.backgroundColor = this.bgColor;
}
private colorText(): void {
const [r, g, b] = convert.keyword.rgb(this.el.nativeElement.style.backgroundColor);
// http://www.w3.org/TR/AERT#color-contrast
const perceivedBrightness = Math.round(((parseInt(r) * 299) +
(parseInt(g) * 587) +
(parseInt(b) * 114)) / 1000);
const foregroundColor = (perceivedBrightness > 125) ? 'black' : 'white';
this.el.nativeElement.style.color = foregroundColor;
}
}