0

I want to add image based on background color in angular. for example something like this->

<span *ngIf = "style :'background-color: #somecolor'"> <img></img></span>

1 Answer 1

1

If your background color is applied from a stylesheet rule, you can get its value by reading element computed style.

Here is a stackblitz example which add the string "(This item is red)" after item value if the element background color is red.
You can apply this logic to your case by replacing the string by an image.

component

export class AppComponent  {
  items = [
    'item 1',
    'item 2',
    'item 3'
  ];

  isRed(element)
  {
    var color = window.getComputedStyle(element).getPropertyValue("background-color");
    return color === 'rgb(255, 0, 0)';
  }
}

template

<ul>
  <li *ngFor="let item of items" #itemRef>
    {{item}}
    <span *ngIf="isRed(itemRef)">(This item is red)</span>
  </li>
</ul>

stylesheet

li:nth-child(1) {
  background-color: red;
}

li:nth-child(2) {
  background-color: green;
}

li:nth-child(3) {
  background-color: blue;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.