I have written a service in which different colors are defined. Now I would like to set a different background for my columns. Using the <th>
tag it is not possible, because immediately both columns get the same colors.
My Code:
change-color-service
export class ChangeColorService {
public defaultStyles = {
firstDesignBackgroundColor: '#25a1b1',
secondDesignBackgroundColor: '#c3c0c0',
};
sharedStyleSource = new ReplaySubject<any>(1);
public sharedStyle = this.sharedStyleSource.asObservable();
constructor() { }
newStyle(obj: any) {
this.defaultStyles[obj.name] = obj.value;
console.log('defaultStyles:', this.defaultStyles);
this.sharedStyleSource.next(obj);
}
}
my-component
public myArray = [
{ attribute: 'firstColumn', name: 'Firstname'},
{ attribute: 'secondColumn', name: 'Lastname'},
];
ngAfterViewInit() {
changeFirst('firstColumn');
changeFirst('secondColumn');
}
public changeFirst(attributeToChange: any) {
const displayedColumn = this.displayedColumns.find((dc) => dc.attribute === attributeToChange);
if (displayedColumn && displayedColumn !== null) {
displayedColumn.attribute = this.changeColorService.defaultStyles.firstDesignBackgroundColor;
}
}
public changeSecond(attributeToChange: any) {
const displayedColumn = this.displayedColumns.find((dc) => dc.attribute === attributeToChange);
if (displayedColumn && displayedColumn !== null) {
displayedColumn.attribute = this.changeColorService.defaultStyles.secondDesignBackgroundColor;
}
}
It does not seem to work that way. Can you tell me how to solve the problem?
I have a solution, but not with your's service!
I have create a method changeColor()
with a parameter. The parameter is the index of the tables-output (in my example, the index from the alphabet array). So the method changeColor()
check against the index, if the index is even (return color-one) or odd (return color-two) to alternate the color every time.
The color can be set in the .ts
file.
public changeColor(index: number): string {
if (index % 2 == 0 ) { // if is even
return "#25a1b1"; // first color
} else if (index % 2 == 1 ) { // if is odd
return "#c3c0c0"; // second color
}
}
The background-color
in the HTML-file I define as follow and set after the background-color
-CSS attribut the method changeColor()
where return one of the both colors:
<tr *ngFor="let element of alphabet; index as i">
<td style="background-color:{{ changeColor(i) }};"> {{ element.name }} </td>
</tr>
Have a look at my stackblitz