Creating Dynamic Background Images with Linear Gradients in Angular 2 Components

In my angular2 rc2 and typescript project, I am facing an issue with setting the color in an angular 2 component using a property.

Within the component, I have converted the color to rgba and created a linear gradient that I intend to set in the template.

import { Component, Input, OnInit } from "@angular/core";

@Component({
      selector: "horizontalrule",
      template : `<div class="fadding-ruller-holder">
                        <hr class="fadding-ruller" [style.background-image]="BackgroundImage">
                  </div>`,
})

export class HorizontalRule implements OnInit
{
      @Input() color:string;

      public BackgroundImage:string;

      constructor(private utils:UtilsService) 
      {

      }

      ngOnInit()
      {
            //color: #FF0000

            let rgba:string = this.ConvertHexToRGBA(this.color, 0.7);

            //rgba: rgba(255,0,0,0.7)

            this.BackgroundImage = "-webkit-linear-gradient(left, rgba(0, 0, 0, 0)," + rgba + "rgba(0, 0, 0, 0))"
                                    + "-o-linear-gradient(left, rgba(0, 0, 0, 0),"   + rgba + "rgba(0, 0, 0, 0))"
                                    + "linear-gradient(to right, rgba(0, 0, 0, 0),"  + rgba + "rgba(0, 0, 0, 0))";
      }

      public ConvertHexToRGBA(hex:string, opacity?:number):string
      {
            opacity = opacity || 1;

            if(opacity < 0) {
                opacity = 0;
            }
            else if(opacity > 1) {
                opacity = 1;
            }

            hex = hex.replace('#','');

            let r = parseInt(hex.substring(0, 2), 16);
            let g = parseInt(hex.substring(2, 4), 16);
            let b = parseInt(hex.substring(4, 6), 16);

            return 'rgba(' + r + ',' + g + ',' + b + ',' + opacity +')';

      }
}

I am encountering issues as the gradient is not being set in the HTML. Can someone please guide me on whether this approach is correct?

Answer №1

import {DomSanitizationService} from '@angular/platform-browser';

class CustomBackground implements OnInit {
  applyBackgroundStyle(style) {
    return this.sanitizer.bypassSecurityTrustStyle(style);
  }

  ngOnInit() {
        //setting color to red

        let rgbaColor:string = this.applyBackgroundStyle(this.convertHexToRGBA(this.color, 0.7));

        //rgba color: rgba(255,0,0,0.7)

        this.BackgroundImage = this.applyBackgroundStyle("-webkit-linear-gradient(left, rgba(0, 0, 0, 0)," + rgbaColor + "rgba(0, 0, 0, 0))"
                                + "-o-linear-gradient(left, rgba(0, 0, 0, 0),"   + rgbaColor + "rgba(0, 0, 0, 0))"
                                + "linear-gradient(to right, rgba(0, 0, 0, 0),"  + rgbaColor + "rgba(0, 0, 0, 0))";)
  }
}

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

Tips for automatically resizing a canvas to fit the content within a scrollable container?

I have integrated PDF JS into my Vue3 project to overlay a <canvas id="draw_canvas"> on the rendered pdf document. This allows me to draw rectangles programmatically over the pdf, serving as markers for specific areas. The rendering proces ...

Two divisions placed side by side

The current structure I am working with looks like this: <div id="container"> <div id="msg"><p>Lorem ipsum dolor sit amet.</p></div> <div id="img"><div id="content"></div></div> </div> # ...

Notifying Subscribed Angular8 Components Based on Logical Conditions with Observables Inside Services

I provide a service that offers a function returning an Observable. Within this service, I have certain logic that should trigger a new call on the Observable to update the data for subscribed components. While I can use next within the Observer construct ...

Minor hiccup in the CSS animation

While creating a CSS animation for a responsive menu icon that transforms into an "X" when clicked, I encountered a minor glitch. The top line of the menu icon flickers down by about 1px after the X shape is formed, causing it to continue moving while the ...

Combine all Angular Material Styles into a single CSS file rather than dynamically loading each style at runtime

I have encountered an issue in my Angular 8 Application where multiple style tags are dynamically generated at runtime for Angular Material. To address this, I am looking to add a CSP attribute to all my style tags after the build process is completed. To ...

How to attach onclick events to newly created div elements using JavaScript

Having some trouble adding click events to multiple dynamically created div elements. After creating divs with ids a0 through an, I want to assign them click events using a for loop. The problem is that when the click event occurs, I can't identify w ...

I recently installed Angular version 12, but another unexpected version 13 was also installed simultaneously. I only wanted version 12, so now I need to figure out how to uninstall

C:\Users\eaind>npm install -g @angular/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="96f5faffd6a7a4b8a6b8a4">[email protected]</a> https://i.sstatic.net/LQPPT.png Upon installing version 12 in the direc ...

Creating a dynamic configuration for service instantiation in Angular 4/5

Currently working on a library that has an AuthModule with an AuthService for managing OAuth2 authentication using oidc-client-js. I want the application using this library to be able to set up the configuration for the OAuth client. One way to do this is ...

Strange occurrences observed with the interaction of multiple CSS classes

Recently, I encountered a situation with a class that had me puzzled. .lifetime .containerrow { text-align: center; height: 20px; } To enhance the appearance of certain elements by making their text bold, I attempted the following: .lifetime .co ...

Shifting the "active" designation within a dropdown menu to correspond with the user's current page

Recently, I decided to explore the Foundation framework. However, my first stumbling block was figuring out how to use the "active" class in a dropdown menu. I am hoping to have the class applied to the page link that is currently being viewed by the user ...

Angular is unable to locate images within the assets directory if they are nested within a subfolder

Despite my efforts to set a default PNG image for users who do not upload their own, I have been unable to get it to display after an hour of troubleshooting. <img src="assets/images/image-card.png" /> I attempted to modify the asset value ...

The anchor tag causes the tooltip to display outside of the td element

One of my requirements is to display the click percentage for each link in an HTML template that is dynamically fetched from a database. I attempted to show the click percentage for each anchor link by adding them to the `data-title` attribute using jQuery ...

How can you create an interface where the value type is determined by the key, but not all keys are predefined?

Below is an illustration of a data structure that I aim to define as a type in TypeScript: const dataExample = { Folder: { "Filename.js": { lines: { total: 100, covered: 80, ...

Create a continuous scrolling tool similar to Google Reader for iGoogle

Do you know how to create an infinite scroll widget similar to Google Reader on iGoogle? This widget should be able to dynamically load data as the user scrolls, and replace the traditional scroll bar with a pair of up and down arrows. The HTML structure ...

Showing content in a single line causes it to drop down to the next

Check out my code snippet here: http://jsfiddle.net/spadez/aeR7y/23/ I'm curious about how I can make my header list align on the same line as the header, without dropping down. Here's the CSS code I have for the list: #header li { display: ...

A Guide on Loading Environment Data for app.modules.ts in Angular

I am looking to retrieve data from a service that includes environment details. Specifically, I need certain data for a module within app.modules. Below is an example from app.modules.ts: import { CustomEnvironmentService } from './CustomEnvironment ...

Fine-tuning the page design

I'm working on a registration page using Bootstrap-5 for the layout. Is there a way to place all elements of the second row (starting with %MP1) on the same row, including the last field that is currently on the third row? See image below: https://i. ...

How to execute a function in a child component that is declared in the parent component using Angular

Is anyone able to help me with an issue I am facing in my Angular project? I have two components, 'app' and 'child'. Within the child component, I have a button that calls a function defined in the app component. However, this setup is ...

How to Use Jquery to Deactivate a Div with a Background Color

Currently, I have a div that contains several child divs. My goal is to disable the parent div and all of its children, showing them in gray color. I initially tried using the CSS property opacity, but unfortunately, the background color didn't change ...

What is the best way to split a div diagonally while keeping the border unchanged?

I'm attempting to devise the design displayed in the link below: https://i.sstatic.net/n0ZbB.png I have experimented with the following code: .App { font-family: sans-serif; text-align: center; } #container { height: 300px; width: 300p ...