Reputation: 11260
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.
Upvotes: 0
Views: 1584
Reputation: 983
Or if you want style more than just one css selector you can use DomSantizer and pass all css style to your Child component
In parent:
<child-component
div1Style='width: 400px;background-color:red;'
div2Style='width: 400px;background-color:red;'>
</child-component>
child component input variable:
@Input() div1Style: string;
@Input() div2Style: string;
in child in html div
<div [style]='GetStyle(div1Style)' >
<div [style]='GetStyle(div2Style)' >
and in code of child component
constructor(private sanitizer: DomSanitizer) { } //to inject instance of this DomSantizer
GetStyle(c) {
if (isNullOrUndefined(c)) { return c; }
return this.sanitizer.bypassSecurityTrustStyle(c);
}
and you can declare as many these variables as you need - one per each div for example
Upvotes: 0
Reputation: 680
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>
Upvotes: 1