Adding square elements to mat-table in Angular

I'm encountering an issue with the mat-table in my project. I want to incorporate squares into the cells, but I'm unsure how to achieve this.

Here is a snippet of my current code:

<div class="my_item">
        <div><span class="skuska"><span class="mat-subheading-2">January</span></span></div>
        <mat-table #table [dataSource]="dataSource" matSort>
          <ng-container matColumnDef="{{column.id}}" *ngFor="let column of columnNames">
            <mat-header-cell *matHeaderCellDef mat-sort-header> {{column.value}} </mat-header-cell>
            <mat-cell *matCellDef="let element"> {{element[column.id]}} </mat-cell>
          </ng-container>

          <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
          <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
        </mat-table>
      </div>

I currently have a table displaying only text, but I would like to replace it with squares containing numbers instead.

Here is a visual representation of what I'm aiming for:

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

Unfortunately, I only have a picture example and not the actual implementation in my table.

If anyone could provide guidance on how to achieve this, I would greatly appreciate it!

Thank you for your assistance!

This is the updated code snippet:

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

Html file

 <div class="my_item">
        <div><span class="skuska"><span class="mat-subheading-2">April</span></span></div>
        <mat-table #table [dataSource]="dataSource" matSort>
          <ng-container matColumnDef="{{column.id}}" *ngFor="let column of columnNames">
            <mat-header-cell *matHeaderCellDef mat-sort-header> {{column.value}} </mat-header-cell>
            <mat-cell *matCellDef="let element" [style.background-color] = "element.color"> {{element[column.id]}} </mat-cell>
          </ng-container>

          <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
          <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
        </mat-table>
      </div>

.ts file

import { Component, OnInit, ViewChild } from '@angular/core';
import { MatTableDataSource, MatSort } from '@angular/material';


@Component({
  selector: 'app-harmonogram',
  templateUrl: './harmonogram.component.html',
  styleUrls: ['./harmonogram.component.css']
})
export class HarmonogramComponent implements OnInit {

  dataSource;
  displayedColumns = [];
  @ViewChild(MatSort) sort: MatSort;

  /**
   * Pre-defined columns list for user table
   */
  columnNames = [{
    id: "po",
    value: "Monday"

  }, {
    id: "ut",
    value: "Tuesday"
  }, {
    id: "st",
    value: "Wednesday"
  }, {
    id: "stv",
    value: "Thursday"
  }, {
    id: "pi",
    value: "Friday"
  }, {
    id: "so",
    value: "Saturday"
  }, {
    id: "ne",
    value: "Sunday"
  }];

  ngOnInit() {
    this.displayedColumns = this.columnNames.map(x => x.id);
    this.createTable();
  }

  createTable() {
    let tableArr: Element[] =
      [
        { po: '', ut: '', st: '', stv: '', pi: '', so: '', ne: '',color: 'black'},
      { po: '', ut: '', st: '', stv: '', pi: '', so: '', ne: '',color: 'green'},
      { po: '', ut: '', st: '', stv: '', pi: '', so: '', ne: '',color: 'grey'},
      { po: '', ut: '', st: '', stv: '', pi: '', so: '', ne: '',color: 'blue'},
        { po: '', ut: '', st: '', stv: '', pi: '', so: '', ne: '',color: 'green'}
      ];
    this.dataSource = new MatTableDataSource(tableArr);
    this.dataSource.sort = this.sort;
  }
}

export interface Element {
  po: string,
  ut: string,
  st: string,
  stv: string,
  pi: string,
  so: string,
  ne: string,
  color: string,
}

This excerpt shows a portion of the .css file used:

.mat-cell{

  height: 26px;
  width: 26px;
  display: inline-flex;
  border-left: 4px solid white;
  padding-left: 0px;
}

Currently, I am able to change the row color, but I specifically need to alter individual cells, such as those containing the value "8" (currently invisible).

Answer №1

Here is how you can implement this in css:

Check out the code snippet here:https://example.com/css-snippet

.mat-cell{
    background-color: green;
    min-height: 26px;
    border-left: 4px solid white;
    padding-left: 9px;
}
.mat-cell:last-child{
     background: linear-gradient(90deg, green 50%, white 50%);
}

To apply dynamic background-color, use [style.backgound]="YourColor"

If it is the last-child (meaning element[column.id]='ne'), use

[style.backgound]="linear-gradient(90deg, 50%, YourColor white 50%)"

For more information, visit:https://example.com/code-example

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

What steps should I take to properly customize ElementView for my own element, ensuring that it displays the desired content and processes the markup correctly without encountering any errors?

I found a jsFiddle with JointJS code that works perfectly for me: https://jsfiddle.net/RaymondMH/s46uyq8v/156/ However, when I attempt to integrate this code into my actual application, none of the functions defined in the ElementView.extend() call are b ...

The modal window does not display a scroll bar

I'm currently facing an issue where the scroll bar is not appearing on my page when more elements are added. In addition, I have a modal that covers the entire page when clicking on an item. However, changing the CSS position: fixed property affects ...

I'm having trouble getting the Bootstrap 5 Carousel to work, even though I directly copied the code from the official website

Currently, I am designing a webpage utilizing Bootstrap 5 and incorporating the CDN for functionality. Although, when attempting to implement their carousel feature, it does not seem to be functioning as expected. The only modification I have made to their ...

When a user chooses an item, the ui-select dropdown appears hidden behind additional fields on the screen

In my AngularJS application, I am utilizing ui-select within a table that repeats rows using ng-repeat. The following code snippet displays how ui-select is implemented: <ui-select name="{{'selProperty' + $index}}" ng-model="thing.property" ...

The navigator's userAgent property is used to match specific handset identifications

When identifying users on specific devices, I use navigator.userAgent.match to detect certain phones. However, with Android devices, there are various tablets, phones, and set-top boxes to consider. So, my code snippet looks like this: if(navigator.userAg ...

Utilizing jQuery for Smooth Navigation Between Page Anchors and IDs

I have a large page with numerous divs, all of the same size and each with a unique ID. Initially, I used jQuery ScrollTo/LocalScroll for navigation between anchors. However, the client now prefers a more subtle transition such as a fade in/fade out effect ...

Angular2: Separate router-outlets within individual modules

I am working on an Angular app that consists of multiple modules (modules A and B are lazy loaded): MainModule, ModuleA, ModuleB Currently, all content is loaded in the AppComponent (which has a router-outlet tag). However, I would like to restructure it ...

Bootstrap's grid width is not aligned properly

I am a newcomer to Boostrap and I find myself in a bit of a sticky situation...I have tried numerous solutions, consulted the Boostrap documentation, but I still require assistance. Here is the code snippet: <link rel="stylesheet" href=" ...

Prevent body scrolling when modal view is activated

As I work on developing this website, I have encountered an issue. Upon clicking a link located at the far right end of the second row in the header, a modal window appears with embedded YouTube videos. The problem arises when scrolling through the modal: ...

How can I pass the color hex value from the controller to the view without using quotation marks?

I'm having trouble sending a value and color pair using JSON. The color value needs to be returned to the JavaScript in the view as color: "#FFFFFF". I can send it to the view that way, but once the browser reads it, it turns into color: &quot;#FF ...

What is the best way to maintain the routerLinkActive state when navigating to another component page that is related to the current page

Why does the navigation link become inactive when routing from myloans to syncmyloans? How can I maintain navigation activation when moving to related sub pages within the main navigation? Navigation <nav> <ul class="navbar-nav ml-auto&q ...

Using Single Quotes as Parameters in JavaScript

I'm currently facing an issue with a function that is designed to populate a field in the parent window when clicked. Specifically, it is meant to fill in a text field with a name. The challenge I am encountering arises when the field contains a sing ...

ideas for adding a button in the midst of several rows

Trying to dynamically add two buttons after the first image in each row of a table using a script. The table is retrieved from a server, and the script should automatically insert the buttons. <html> <body> <tr style="background:#EEE;li ...

Problem with full-page navigation sliding in and fading in and out

Upon the user's click on <a href="#slide-nav" class="slide-nav-trigger">, a full-page navigation smoothly slides into view. This animation is triggered by CSS and uses jQuery for event delegation. The Dilemma Instead of abruptly turning on and ...

Automatically clicking the YouTube play button upon loading the video

Can anyone help me with automatically clicking the YouTube play button upon page load on a mobile device? I am currently using an iframe to display the YouTube video, which is set to autoplay on desktop but shows the play button on mobile devices. <s ...

Guide to generating dynamic multiple fields in AngularJS

I have an AngularJS app where I am adding multiple dynamic fields within a form. Here is how I have tried to do it: The JavaScript file looks like this: $scope.commonData = [{ 'a': '', 'b': '', }]; $scope. ...

What's causing the text not to wrap when using float?

I've tried setting float:left for the image and float:right for the text, but the image is still overlapping the text. What I really want is for the text to wrap around the image - to be on the right side of the image at the beginning and below the i ...

Tips for incorporating unique images into each individual flex box

I am new to the world of coding, having just embarked on this journey less than a week ago. Following a tutorial by a developer on YouTube, I tried to add my own twist to the project in order to differentiate it from the original. However, I've hit a ...

Other options for setting a background image in HTML emails aside from utilizing the background-img URL and avoiding the use of divs

I am struggling with creating the header section for an HTML email that is currently under construction. I am using background-img url for the image with content overlay, but unfortunately Outlook 2007, 2010, and 2016 do not support background-images on ta ...

When I start the Chrome debugger, my breakpoints do not appear on the screen

Using IDE Visual Studio Code Reviewing tsconfig.json settings: { "compileOnSave": false, "compilerOptions": { "baseUrl": "./", "outDir": "./dist/out-tsc", "sourceMap": t ...