Is it possible to utilize the lighten css property within ngStyle in Angular?

Having some trouble with the lighten property in ngStyle and it's not working as expected.

I have a color variable within my component that I want to utilize like so:

<div [ngStyle]="{color: schedule.group.color, background: 'lighten(' + schedule.group.color + ', 50%)'}">

Any ideas on how to make this work properly?

Answer №1

There is no built-in "lighten" function in CSS, as it is typically associated with Less or Sass. However, there are JavaScript functions available online for achieving this effect, such as this one on css.trick

UPDATE Important! (change the function)

  /**Credits to: https://css-tricks.com/snippets/javascript/lighten-darken-color/ */
  //amt from 0 to 100
  lightenDarkenColor(col, amt) {

    amt=256-Math.floor(amt*5.12)
    const  usePound = col[0]=="#";
    if (usePound)
        col = col.slice(1);

    const num = parseInt(col,16);

    const rr=(num >> 16) + amt;
    const  bb = ((num >> 8) & 0x00FF) + amt;
    const  gg = (num & 0x0000FF) + amt;

    const r=rr>255?255:rr<0?0:rr;
    const b=bb>255?255:bb<0?0:bb;
    const g=gg>255?255:gg<0?0:gg;

    if ((g | (b << 8) | (r << 16))==0)
        return "#000000";

    return (usePound?"#":"") + (g | (b << 8) | (r << 16)).toString(16);

  }

Use

<div [ngStyle]="{color: color, 'background-color': lightenDarkenColor(color, 10)}">hello word</div>
<div [ngStyle]="{color: color, 'background-color': lightenDarkenColor(color, 90)}">hello word</div>

see demo in stackblitz

Answer №2

In some cases, the function mentioned above returns a white color, but I managed to find a solution for this issue:

convertHexToRGBA(hex: any, alpha: any): string {
    let hexCode = hex.replace('#', '');
    hexCode =  hexCode.match(new RegExp('(.{' + hexCode.length / 3 + '})', 'g'));

    for (let j = 0;  j < hexCode.length; j++) {
        hexCode[j] = parseInt(hexCode[j].length === 1 ? hexCode[j] + hexCode[j] : hexCode[j], 16);
    }

    if (typeof alpha !== 'undefined') { hexCode.push(alpha); }

    return 'rgba(' + hexCode.join(',') + ')';
}

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

Utilizing tag keys for inserting text and adjusting text sizes within a Web application

Creating an online editing interface for coursework where keyboard events are used. The goal is to have the tab key insert text, while also reducing the size of the text on that line. However, upon using getElementById, an error message pops up stating: ...

I'm encountering an issue where it appears that my ajax method may not be effectively communicating with my webservice

I am currently working on calling a webservice using an ajax request with the intention of retrieving clinical cases within a specific date range (for example, between 2015-01-01 and 2016-06-08). The webservice functions perfectly when tested individually. ...

I am interested in incorporating a vertical scrollbar into a gridview in ASP.NET

I've successfully bound data to a grid view in my ASP.NET application. I've implemented pagination, but instead of that, I'd like to incorporate a scroll bar to prevent lengthy paging. Below is the code for my grid view: <div class="box ...

Here is a unique rewrite:"Adjusting the prop of a Material UI Button component depending on screen size breakpoints can be achieved by utilizing

While using the Material UI Button component, I encountered an issue with conditionally determining the variant of the button based on screen size. Specifically, I want the variant to be 'outlined' on medium and larger screens, and no variant at ...

What is the process for passing input values to a dynamic Angular component?

My goal is to develop a dynamic filtering system where users can specify multiple attributes and their corresponding values to filter a list of components. The dynamically added component includes two dropdown menus: one for attribute selection and another ...

When the class changes, V-for re-renders every component

Currently, I am in the process of changing classes for images based on their index using the moveIndex method and key events. While this works smoothly on computers, it seems to take significantly longer when implemented on TVs. The process runs smoothly w ...

The absence of a meta tag in the Wordpress head section

I keep getting an error from Lighthouse saying that I am missing both the viewport meta tag and description meta tag Does not have a <meta name="viewport"> tag with width or initial-scaleNo `<meta name="viewport">` tag found ...

Angular2's customer filter pipe allows for easy sorting and filtering of

Check out the component view below: <h2>Topic listing</h2> <form id="filter"> <label>Filter topics by name:</label> <input type="text" [(ngModel)]="term"> </form> <ul id="topic-listing"> <li *ngFo ...

MVC Template with a Defective BootStrap

Struggling with creating an MVC master template along with sub-pages using Bootstrap. Sadly, I seem to have messed it up and can't quite figure out where the problem lies. You can check out my test website at Do you see how the different sections a ...

Tips on how to loop a song continuously in jPlayer's circular mode

Can you help me figure out how to make a song repeat in jPlayer circle? I have the code for autoplay, but I also want to add a repeat functionality. I tried adding options like repeat:, but it didn't work as expected. <script type="text/javascript ...

Creating an image in jpg format from an html file using a button

I have a unique HTML code for an email signature from my company and I am looking to add a button that can generate a JPG or PNG image of the signature without having to resort to PrintScreen and manual cropping in editing tools like Paint or Photoshop. Ho ...

What is the process for changing text to red when hovering over it in a nested list?

a { color:black; } a:hover { color:red; } <ol> <a href="#"><li>Main1</li></a> <a href="#"><li>Main2</li> <a href="#"><li>Main3 <ol> ...

What is the best way to transfer data to the server in a loop without encountering synchronization issues?

I am working with an array of products in typescript (in angular) and my goal is to update their prices in the database using http calls. The way I currently insert them is as follows: array.foreach(element=>{ this.product.price=element; this.myS ...

Achieving nested classes in CSS: a comprehensive guide

I am encountering an issue with my CSS while trying to create a dropdown on hover. The problem seems to be related to nested classes inside a div structure. It appears that the dropdown list is not displaying properly, leading me to believe there might be ...

I am experiencing an issue where the repeat-x property on my background image is causing it

Currently, I'm facing an issue with a background image that has the repeat-x property. Oddly enough, it appears to be working properly on Windows OS but not on Mac. Whenever I access the website, there seems to be a significant amount of white space c ...

Using Angular's ngModelChange along with a button to reset the input field

In the backend, there is a text input that I use to search for data. Whenever something is typed into the input field, a clear button appears to reset the value of the field. Additionally, there is a log that shows the content of the input when characters ...

Tips on concealing all classes except one through touch swiping

If you have a website with a single large article divided into multiple sections categorized as Title, Book1, Book2, & Book3, and you want to implement a swipe functionality where only one section is displayed at a time, you may encounter some issues. ...

The unit test is running successfully on the local environment, but it is failing on Jenkins with the error code TS2339, stating that the property 'toBeTruthy' is not recognized on the type 'Assertion'

I've been tackling a project in Angular and recently encountered an issue. Running 'npm run test' locally shows that my tests are passing without any problems. it('should create', () => { expect(component).toBeTruthy();}); How ...

Unable to access material datepicker by its element id within ngAfterViewInit function

Upon component loading, I am attempting to open the material DatePicker using its element ID (#). However, when I use ngAfterViewInit, it consistently returns an error stating 'Cannot use 'open' on undefined'. Interestingly, the DatePic ...

Troubleshooting a problem with Angular 2's ng-select component within a ReactiveForms when working with an array of

I am struggling to retrieve data for the ng-select component. <ng-select [allowClear]="true" [items]="tempArrayUoM[i]" formControlname="uom" [active]="initialUoM[i]" placeholder="UoM"> </ng-select> Could someone assist me in underst ...