Pascal
Pascal

Reputation: 12865

Bind rgb color value with angular 2 style binding

I want to bind a rgb value like "200,55,100" coming from backend to the to the background color of a div.

That does not work, it throws template parse exception.

<div [style.background-color]="rgb({{model.color}})"

How do I do that correctly?

UPDATE

<div [style.background-color]="s.getColor()"> class="md-chip" *ngFor="let s of sums">
    <div class="md-chip-img">
        <span style="text-align:center" class="md-chip-span">X</span>
    </div>
    <span class="md-chip-text">{{s.subjectName}}</span>
</div>

Upvotes: 3

Views: 15007

Answers (2)

daniel.caspers
daniel.caspers

Reputation: 1756

I had a similar case of needing client color conversion bound like an attribute directive.

In my case, I used to require this functionality and before Angular, I relied on jQuery to convert the color I set in keywords to RGB for auto-contrasting text on a background. If you need to do the color conversion, check out color-convert on npm.

If you tweak the color conversion in colorBackground() and colorText() you should be able to do the same.

If you want to see how its used and works, you can check out this stackblitz I was sketching in.

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

Upvotes: 0

Sjoerd
Sjoerd

Reputation: 1305

You cannot use property binding (the [] syntax) and interpolation (the {{}} syntax) together. The reason for this is that Angular2 creates a property binding behind the scenes for the interpolation (see also Angular2 docs on interpolation).

I would suggest to try the following with interpolation:

<div style.background-color="rgb({{model.color}})">...</div>

Or if you want to use the property binding, the following should work:

<div [style.background-color]="'rgb(' + model.color + ')'">...</div>

Where getColorString() is a method that returns the computed string for your rgb value:

public getColorString(): string {
  return 'rgb(200, 55, 100)';
}

Upvotes: 8

Related Questions