Incorporate an image icon into an Angular grid

Currently, I am in the process of building a web application using Angular. The main goal is to create a grid and color specific cells based on data input.

Below is the snippet of 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 the TypeScript code that complements the above HTML 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";
}
}

The functionality is working as expected so far.

https://i.sstatic.net/p8PFa.png

I now have a requirement to include an image icon within the red-colored cells but I haven't found a solution yet.

Answer №1

Have you experimented with using background: backgroundVariable instead of background-color.

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

Check out this helpful tool for converting images to data URIs: Data:image maker

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

CSS
background: backgroundVariable;

Answer №2

One effective solution would be to leverage Bootstrap for this task. For a step-by-step guide on how to incorporate it, refer to the following link: How to programmatically use bootstrap icons in an angular project?

An example of the final implementation is shown below:

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

Answer №3

Task completed. The Typescript code has been updated:

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 has also been revised as follows:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can you explain the significance of using an exclamation mark after defining a variable in TypeScript?

As I delve into TypeScript in an effort to enhance my programming skills, I have encountered the use of exclamation marks when defining variables. An example of this can be seen in the following code snippet: protected _db!: CheckpointDB ...

Execute the function when the element comes into view

Is there a way to create a function that will automatically attach itself to an element when it comes into view? I have multiple elements on my page - element1, element2, and element3. Instead of using a large if statement, I would like to write a functio ...

Having trouble retrieving POST data with NodeJS/Express and an HTML form?

I have encountered an issue in my application where I am unable to extract the posted data from req after performing an action pointing to a nodejs endpoint. Despite successfully executing the action, when attempting to access the posted data from req, I a ...

Utilizing electron and Systemjs to import node modules

Is it feasible for systemjs to utilize require("remote").require("nodemodule") when the module cannot be located in its registry? A similar mechanism seems to be functioning when utilizing electron with typescript and commonjs modules... Has anyone succe ...

What could be causing the 404 error when trying to make a get-request to fetch a list of all users?

Having trouble retrieving a list of users using my endpoint, as it keeps returning a 404 error. I have set up a model, controller, router, and index file for the user in my application. Below is the User.ts model: import { Schema } from 'mongoose&apo ...

TypeScript's TypeGuard wandering aimlessly within the enumerator

I'm puzzled by the fact that filter.formatter (in the penultimate line) is showing as undefined even though I have already confirmed its existence: type Filter = { formatter?: { index: number, func: (value: string) => void ...

The correct way to add to a string array that has been passed as props to a functional component

There is a parent component that establishes a useState hook with a string array. Then, there is a child component tasked with updating the string array. To accomplish this, both the string array and the useState function are passed to the child component. ...

How to simulate keyboard events when a dropdown list is opened in an Angular application

Requirement- A situation arises where upon opening the dropdown menu, pressing the delete key on the keyboard should reset the index to -1. Steps to reproduce the issue: 1. Click on the dropdown and select an option from the menu. 2. Click on the dropdow ...

Adding an item into a list with TypeScript is as simple as inserting it in the correct

I am working with a list and want to insert something between items. I found a way to do it using the reduce method in JavaScript: const arr = [1, 2, 3]; arr.reduce((all, cur) => [ ...(all instanceof Array ? all : [all]), 0, cur ]) During the fir ...

Discover the power of native script's two-way data binding in your classes

Is there a way to implement two-way binding in Nativescript? Here is my attempt: The variable CompModel is set to "FA I Test". I am looking for a solution where the data can be bound both ways - initially displaying the value "FA I Test" at the class lev ...

Modifying the href in Django according to the current page URL: a step-by-step guide

Like the title suggests, I'm curious about the proper way to dynamically change a link's href based on the current URL that the user is visiting. I attempted a solution, but it proved unsuccessful. {% if url == '' %} href='/cooki ...

Creating custom style sheets in Smarty

The formatting of a template processed in Smarty is being lost Previously (viewed in notepad++): <!DOCTYPE html> <html lang='ru'> <head> Now (displayed in the browser): <!DOCTYPE html><html lang='ru'&g ...

Text positioned in a fixed location

How can I ensure that the main content stays on the right side of the sidebar without adding margin-right? Currently, the sidebar is being covered by the body content due to its fixed position. Is there a solution to prevent this issue? .App { displa ...

When the button is clicked, I would like to use JavaScript to toggle the visibility of a div, allowing it to open and

I am attempting to toggle a div using JavaScript when the open and close button is clicked. However, I have encountered an issue where the div disappears when the button is clicked, possibly due to post-back. var toggle = function () { var mydiv = d ...

Is there a way to locate multiple buttons on a webpage that have the same id and field name but varying values using selenium?

On my webpage, I am looking to interact with four submit buttons. All four buttons have identical Id and name attributes, with the only difference being their values. Is it possible to locate and handle these elements using Selenium WebDriver? (Consideri ...

Keys preset in TypeScript using keyof

I need a set of predefined keys, but users should not be restricted to only using those keys. type B = { a: string; b: number; } type T = keyof B | string; function someFunc(key: T) {} someFunc(); // key type is `T` In the scenario above, I am lo ...

Page resizing is disabled in Chrome after an Ajax load

I've been tirelessly working on the CSS for a website I'm building, and I've encountered a strange issue that only seems to affect Chrome. Firefox and Internet Explorer work perfectly fine. I am using jQuery to load HTML stubs and a signifi ...

What is the reason buttons in mat-menus do not submit?

I have implemented a mat-menu to showcase a list of choices for the user. The objective is to trigger the submission of my formGroup when a user selects an option from the menu. dropdown.component.html <form [formGroup]="myForm" (ngSubmit)=onSubmit(my ...

Using global variables in local Angular-cli components by importing them

Here is an example of my folder structure in Angular CLI: MyApp/ src style/ page/ normalize.less styles.less In my angular-cli.json file, I have the following configuration: "app":{ "styles": [ "./style ...

Position text on the background image without using positioning techniques

I need to center my text precisely on top of my background image without resorting to the use of relative or absolute positioning. Many solutions online rely on using absolute positioning for the text along with a specified top value, but I prefer not to e ...