Im trying to change the color of a cell within a table once clicked using the following:
<table style="border: 1px solid black;">
<thead>
<tr style="border: 1px solid black;" *ngFor="let row of tableData">
<td style="border: 1px solid black;"
*ngFor="let column of row" class="{{ column }}"
[ngClass]="{'selected': column == val }"
[ngClass]="{'toChange': clicked}"
(click)="clicked = !clicked">
{{ column | uppercase }}
</td>
</tr>
</thead>
</table>
When each cell is created during the loop, It also has a click event added to it corresponding to the css styling. However, once a cell is clicked I get no change in color at all.
For reference the css is:
toChange {
background-color: blue;
}
Anyone care to explain to me why my code doesn't work? Many thanks!
You can combine conditional styling with Angular's property and event binding by using NgStyle and NgClass directives using the Angular template syntax.
The NgClass and NgStyle directives are used to apply style to the HTML element conditionally. The NgClass allows you to apply whole class based on condition whereas NgStyle gives you more flexibility to set individual properties.
The ng-class directive dynamically binds one or more CSS classes to an HTML element. The value of the ng-class directive can be a string, an object, or an array. If it is a string, it should contain one or more, space-separated class names.
The NgStyle directive lets you set a given DOM elements style properties. This sets the background color of the div to green. The above code uses the ternary operator to set the background color to green if the persons country is the UK else red.
You do have two [ngClass]
directives. Put them into a single one and separate them with commas like this:
[ngClass]="{'selected': column == val, 'toChange': clicked}"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With