Home > Net >  Dynamically add colors into component
Dynamically add colors into component

Time:11-03

I have 2 components. The first component sets colors that I then use in my second component however I have to set every color individually which I do not want to do. I am trying to possibly add an array that I can add the colors inside instead of adding individual colors.

Here is my code

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>

So basically I do not want to have to add each color individually eg. In the above code I am adding red, grey and orange and if I want to add a new color then I will have to make a new entry. How can I just keep it generic and then add the color like this for example?

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

CodePudding user response:

You can use HostBinding. Example (try me):

Parent:

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';
}

Child

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

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

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