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

Assist with JavaScript Programming

Can someone assist me in creating functionality for the "Show Picture" button to toggle the visibility of the picture when clicked? I've been trying to achieve this using an If/Else statement for a school project but have been struggling with it. Any ...

Is less.js capable of compiling CSS code that is compatible with all browsers?

Is there a simple way to convert my Less code into browser-compatible CSS like the example below? #grad1 { background: -webkit-linear-gradient(red, blue); /* For Safari 5.1 to 6.0 */ background: -o-linear-gradient(red, blue); /* For Opera 11.1 to ...

Shifting the form to the bottom right corner

Just starting out with HTML5 and CSS, I've been experimenting with different elements. One project I've been working on is a form: <div id="form1"> <form action="demo_form.asp" autocomplete="on" > Departure City & ...

Pressing the reset button will restore the table to its original

As a new React developer with experience mainly in hooks, I have been struggling to find a good example involving hooks. Currently, I am working on implementing an antd table with search functionality. My question is, when a user types something into the ...

CSS: Eliminate unnecessary space at the top by implementing a margin and padding reset

I am puzzled by the presence of approximately 10px of whitespace at the top of my HTML file. Despite setting margin and padding to 0 in the "body" section of my CSS, the whitespace persists. Any suggestions? Thank you! Update: I discovered that removing t ...

What is the best way to create a single column for each item in a foreach loop with bootstrap?

I am working on a web development project for my school where I need to create a Trello-like application. I am having trouble figuring out how to generate one column per element in my foreach loop to display the board with different columns. Any guidance o ...

Invoking a Components function from a Service in Angular may lead to a potential cyclic dependency issue

I am facing a challenge where I need to call a function from my filterComponent(component) within my engagementService(service). The function in my filterComponent accesses an array that is located within the engagementService. It uses the data from this ...

Is it possible to retrieve the value of a particular field from a table?

My goal is to create a table that displays data about various users awaiting admin approval. Each row represents a specific user, and when the approve button on a particular row is clicked, I want to open a new window displaying detailed user information f ...

Ensure that only the admin is able to make something vanish for everyone else

Is there a way to hide content for everyone except the admin? Currently, I have this code implemented but it only works when a user is not logged in. When another user logs in, the content is still visible. <?php if( isset($_SESSION['username&a ...

Adjusting the text color of cells in a table based on their values using Ruby on Rails

I have a cell within a table that is formatted like this: <td><%= play_result.timestamp.strftime("%H:%M:%S") + ' ' + play_result.status + ':' + ' ' + '[' + play_result.host + ']' + ' ' ...

The ngFor directive in Angular2 consistently collapses the identical <tr> element

Greetings, I am a newcomer to the world of web development. Recently, I used the *ngFor directive in Angular to generate multiple rows with collapsible details. However, when I click on a row, it always collapses the same div, instead of the corresponding ...

Tips for using jQuery dropdown menus

I am currently in the process of creating a prototype for a quick dropdown menu using jQuery. However, I have reached the limits of my knowledge on jQuery and could use some assistance in solving my issue. My objective is to have a dropdown animate down w ...

Stacking background images in CSS above other contained elements in a div

I've been experimenting with adjusting the z-index of elements in my code but haven't had any luck. Is it even possible to achieve what I want? Within a div element, I have set a background image using CSS. Inside this div, there are other eleme ...

How do I view a wildcard in my ID selector using jQuery?

When I want to initially hide various content scattered around the page, I usually use the following jQuery code: $('#objective_details, #time_estimate_details, #team_members_details, #resources_details').hide(); Is there a method to utilize a ...

Enhanced HTML5 semantic functionality available for all browsers requiring it

There is a tool called HTMLshiv that we are instructed to use with IE9- but it seems that older versions of other browsers do not fully support those tags. Is there a combined conditional statement that can be used for all browsers? If HTMLshiv only work ...

Is it possible to categorize elements for focus and onblur events?

In my search feature, I have implemented an autocomplete div that appears when the user types in a search field. The issue I am facing is that I want the div to disappear when the user clicks outside of it. Here is what I have attempted: //SHOW THE DIV WH ...

Choosing between map and switchMap in RxJS can impact the outcome of

I've been diving into the documentation for both switchMap and map, but I'm struggling to grasp the distinction between the two. Can someone please explain any scenarios where their usage is interchangeable? ...

Right-align SELECT-OPTIONS text

Here are the screenshots of the form I'm currently working on. I am aiming to create a select box in the form where the text within the options is aligned to the right. After an option is selected, the chosen text should be displayed as illustrated i ...

The jQuery click event does not fire within a bootstrap carousel

I am trying to set up a bootstrap carousel where clicking on an image inside it will trigger a self-made lightbox. However, I am facing some issues with the JavaScript code not being triggered with the following syntax: $('html').on("click", ".l ...

Learn how to toggle between two different image sources with a single click event in JavaScript

If the button is clicked, I want to change the image source to one thing. If it's clicked again, it should change back to what it was before. It's almost like a toggle effect controlled by the button. I've attempted some code that didn&apos ...