Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(click) and [ngClass] not changing table cell color

Tags:

angular

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!

like image 349
Jan van Bergen Avatar asked May 17 '18 09:05

Jan van Bergen


People also ask

Can we use NgClass and NgStyle together?

You can combine conditional styling with Angular's property and event binding by using NgStyle and NgClass directives using the Angular template syntax.

What is difference between NgStyle and NgClass?

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.

How does the NgClass work in Angular?

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.

How does NgStyle work?

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.


1 Answers

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}"
like image 196
Jan B. Avatar answered Oct 06 '22 00:10

Jan B.