Inject colors dynamically into component

I currently have two components in my project. The first component is responsible for setting colors which are then used in the second component. However, I find it tedious to set each color individually and am looking for a more efficient solution. I am considering using an array to store all the colors instead of adding them one by one.

Below is the code snippet:

Component 1 HTML

<div [ngClass]="{'brand-error-image-banner': data?.redImageBanner, 'graphite-grey-image-banner': data?.greyImageBanner, 'graphite-orange-image-banner': data?.orangeDarkImageBanner}</div>

Component 1 SCSS

.brand-error-image-banner {
    background-color: $brand-error;
    height: 164px;
    margin: -24px -24px 24px;
}

.graphite-grey-image-banner {
    background-color: $graphite-3;
    height: 164px;
    margin: -24px -24px 24px;
}

.graphite-orange-image-banner {
  background-color: $brand-orange-light;
  height: 164px;
  margin: -24px -24px 24px;
}

Component 1 Modal

export class Component1{
  public redImageBanner: boolean = false;
  public greyImageBanner: boolean  = false;
  public orangeDarkImageBanner: boolean  = false;


  constructor(args) {
    this.redImageBanner = args.redImageBanner;
    this.greyImageBanner = args.greyImageBanner;
    this.orangeDarkImageBanner = args.orangeDarkImageBanner;
  }
}

Component 2 HTML

<component1 [data]="{orangeDarkImageBanner: false, redImageBanner: true, greyImageBanner: false}"></component1>

In essence, I want to avoid specifying each color separately as shown in the example above. Is there a way to make it more generic so that I can simply add a color like this?

<component1 [data]="{color: graphite-orange-image-banner}"></component1>

Answer №1

If you want to dynamically bind a style property in Angular, you can make use of HostBinding. Here is an example for better understanding (give it a try):

For the Parent component:

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `<hello [data]="{ color: selectedColor }"></hello>
  <label for="colors">I am parent color chooser:</label>
  <select name="colors" id="colors" [(ngModel)]="selectedColor">
    <option value="red">red</option>
    <option value="blue">blue</option>
    <option value="green">green</option>
    <option value="orange">orange</option>
  </select>`,
})
export class AppComponent {
  selectedColor = 'red';
}

For the Child component:

import { Component, HostBinding, Input } from '@angular/core';

@Component({
  selector: 'hello',
  template: `<h1>I am the child component!</h1>`,
})
export class HelloComponent {
  @HostBinding('style.color') // you can also bind class names if needed
  color: string;

  @Input()
  set data({ color }) {
    this.color = color; // you could define your logic to map strings to colors here
  }
}

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 is the equivalent variable in Angular for storing session values, similar to PHP's $_session variable

After logging in to my Angular application, I'd like to store user session values. Coming from a PHP background, I am familiar with storing session values using $_SESSION. Can anyone provide guidance on how to achieve similar functionality in Angular ...

PHP loader encountered an error: Module "." not found

My current challenge involves attempting to utilize a PHP file instead of an HTML file as the templateUrl for an Angular component. ... @Component({ selector: 'app-register-form', templateUrl: require('php-loader?./register-form.compone ...

Deciphering the hierarchy of z-index stacking

I'm feeling a bit puzzled about how to determine the stacking order using z-index. I am struggling to grasp how browsers handle elements with the position property in comparison to those without it. Is there a set rule to establish the stack order o ...

What is the best way to ensure that two contact fields are capable of adapting

Looking for a way to center two fields ("Call Us" and "Our Email") while also ensuring they are responsive on different screen sizes? The goal is to have them stack one on top of the other when viewed on a small screen. Even though inline CSS has been used ...

How to create nested nav menus that are optimized for touch-screen devices?

When it comes to creating responsive websites, one challenge I frequently encounter is designing a multi-level nav menu that functions effectively for touch devices. Many plugins and methods exist, but most fall short because they do not allow a second-l ...

How to adjust the banner image placement in Squarespace

I need the banner image to shift position on smaller screens, specifically those with a max-width of 414px. I want the focus to be on showcasing a specific product (a building) located on the right side of the image. This building should only appear on wid ...

Reposition text below images in Meta Slider

I have a website where I am utilizing Meta Slider within Wordpress. I would like to position the captions below the images instead of on top of them. Meta Slider claims this feature is only available in the Pro version, but could it be achieved by adjustin ...

Looking for straightforward tips on parsing CSS code

Seeking advice on how to extract rules and property/values from a .css file or <style></style>. I am not in need of an elaborate parser, as the validity of selector text, property name, or value is not important. My main focus is ensuring that ...

Is there a way I can finish animating these divs in a diagonal motion?

I successfully made the blue and red divs move diagonally and switch positions. Now I am looking to achieve the same effect with the green and pink divs using a similar function. I am unsure about setting the position of both divs to 0 and 350 for those p ...

Why does my 'click' event listener only work for the first two <li>'s and not the others?

I am new to programming and recently achieved success with my 'click' eventListener. When clicking on the first two li elements within the ul, the class of the div toggles on and off as expected. However, I encountered an issue where clicking on ...

List style image does not serve its intended purpose

I attempted to personalize my webpage by adding an image to a list, but I couldn't get the list-style image to work. You can view the page at Below is the code I used: CSS /* Fleet List */ ul#flotta li { list-style-image:url("http://ctp.serviziew ...

Guide to incorporating a Menu feature into your MVC 5 application

After creating an MVC 5 project, the decision was made to change the menu by incorporating Bootswatch. The desired menu to implement is displayed below: https://i.sstatic.net/2vqxn.png The initial step involved modifying the general style of the project ...

Is there a way to adjust the height relative to the viewport in Bootstrap 5 for values other than 100?

Attempting to create a new type of div using a custom stylesheet with minimal non-bootstrap css. I am trying to convert each style rule from my django static files CSS into a bootstrap class, but I am stuck on viewport-based sizing. Prior to discovering t ...

Unable to retrieve information from the redux store

I'm having trouble accessing a property from a Redux store while working with Angular. Within the IApp interface, there are two properties: one is an interface and the other is a number. interface AppStoreInterface { layoutInterface: LayoutInterfa ...

Learning how to merge two observable streams in Angular2 by utilizing RxJS and the powerful .flatMap method

Within my Angular2 app, I have created an Observable in a Service called ContentService. Here is a simplified version of the code: @Injectable() export class ContentService { constructor(private http:Http, private apiService:ApiService) { th ...

"Exploring data trends with an ng2-charts line graph displaying x and y axis values

I am attempting to showcase a function using ng2-charts, with a specific set of x and y values. However, the display is currently not showing my values correctly. https://i.sstatic.net/1iULy.png Here is an example dataset: chartDataSet: ChartDataSets[] = ...

One of the quirks of Angularjs is that the ng-enter animation will only be

The initial animation only occurs the first time. I am utilizing Angularjs version 1.2.22 Here is the CSS that I am using : .ng-enter { animation: bounceInUp 2s; } .ng-leave { animation: bounceOutUp 2s; } And this is the route configuration : ...

After the assignment, TypeScript reordered the elements of the array

Dealing with an array of objects for use in a ngFor loop has presented a challenge. The issue arises when the order that was initially set for the array changes unexpectedly due to JavaScript manipulation. Originally, the array is ordered as expected when ...

The method getDay is not recognized as a function in Typescript Angular

After searching for a solution, I came across a similar question that did not address the specific issue I am dealing with. The challenge I am facing involves parsing a date into a string. Below is my current implementation: export class DataFormater { ...

Circular Dependencies in Angular (only the file name)

Previously, I used to keep interfaces and services in separate files but later combined them into one file since they were always requested together. For example, instead of having user.interface.ts and user.service.ts as separate files, I now have all the ...