WCM
WCM

Reputation: 625

Add image icon to Angular grid

I am developing a web application using Angular. What I am going to do is draw a grid and color specific cells according to some data.

Here is my HTML code

<mat-grid-list cols="10">
<mat-grid-tile *ngFor="let cell of cells" [style.background]="cell.color" [ngStyle]="{'background-color':getCellColor(cell)}">
  {{cell.id}}
</mat-grid-tile>

Here is my typescript code

getCellColor(cell){

var withinA = false;
var withinB = false;

if (this.distance >= cell.minDistanceToA && this.distance <= cell.maxDistanceToA && this.distance > 0 ) {    
  withinA = true;
  
} 
if (this.distance2 >= cell.minDistanceToB && this.distance2 <= cell.maxDistanceToB && this.distance2 > 0 ) {
  withinB = true;
}
if(withinA && withinB){
  return "red";
}
else{
  return "green";
}
}

This is working fine.

enter image description here

Now I want to add an image icon to this red-colored cell. I tried but still no solution.

Upvotes: 0

Views: 1438

Answers (3)

WCM
WCM

Reputation: 625

Solved. Typescript code should be as below

getCellUrl(cell){

var withinA = false;
var withinB = false;

if (this.distance >= cell.minDistanceToA && this.distance <= cell.maxDistanceToA && this.distance > 0 ) {    
  withinA = true; 
} 

if (this.distance2 >= cell.minDistanceToB && this.distance2 <= cell.maxDistanceToB && this.distance2 > 0 ) {
  withinB = true;
}

if(withinA && withinB){
  return "../assets/images/user.jpg";
}

else{
  return "../assets/images/default.jpg";
}

}

The html code should be as below

<mat-grid-tile *ngFor="let cell of cells" [style.background]="cell.color" [ngStyle]="{'background-image': 'url(' + getCellUrl(cell) + ')', 'background-color': 'green'}">

Upvotes: 0

lawrimon
lawrimon

Reputation: 11

I would suggest using Bootstrap for this. A quick answer to how to install it can be found here: How to programmatically use bootstrap icons in an angular project?

The implementation at the end looks like this:

<i class="bi bi-instagram"></i>

Upvotes: 1

Nick Scholten
Nick Scholten

Reputation: 61

Have you tried making it background: backgroundVariable instead of background-color.

Then asign a variable to the background property. For the image use the value of url(link), and for the color the one you already have.

Example for background with image icon: Good data:image maker

JS
var backgroundVariable = "url(data:image/yourOwnImage)"

CSS
background: backgroundVariable;

Upvotes: 1

Related Questions