Search code examples
cssangularng-style

Angular/CSS Style parts of a component dynamically


I have a component, that has different parts. However, I want to be able to style the individual components with different colors.

For instance:

<div class="OuterBox">
    <div class="InnerBox1"></div>
    <div class="Seperator"></div>
    <div class="SecondBox">
        <div class="TextInfo"></div>
    </div>
</div>

I add this to a page, via a standard Angular component:

<app-my-component></app-my-component>

I have seen the ngStyle option for Angular which I could use to specify , but my problem is I cannot simply do a <app-my-component [styles]="{backgroundColor: 'blue', 'font-size': '16px'}">. I need to color the different div sections differently, for instance the InnerBox1 has a background of green, and the SecondBox background should be red.

I can do these styles on the individual CSS, but when I want to make this a common component, I want to be able to change the colors on each instance, so they can be different from green and red, and could be blue and orange or something else.


Solution

  • You can simply declare a variable for each color in your component and bind them from outside In your component :

    import { Component, Input } from '@angular/core';
    @Component({
      selector: 'app-my-component',
      template: `<div class="OuterBox" [ngStyle]="{backgroundColor: outerBoxColor}">
        <div class="InnerBox1"></div>
        <div class="Seperator"></div>
        <div class="SecondBox">
            <div class="TextInfo"></div>
        </div>
    </div>`
    })
    export class MyComponent {
      @Input() outerBoxColor;
    }
    

    and then pass the color from outside like this:

    <app-my-component [outerBoxColor]="'blue'"></app-my-component>
    <app-my-component [outerBoxColor]="'red'"></app-my-component>