Anna F
Anna F

Reputation: 1683

How to use ngClass with table in Angular

I have a table, where I want to declare ngClass (first row)

<table [ngClass]="{'before_forth': pageNumber < 4, 'forth': pageNumber = 4}">
    <tr id="words" *ngFor="let item of itemsSource3; let i = index;">
      <td *ngFor="let item2 of helper[i]; let j = index;">
        <input class="resizedTextbox" name="{{i}}{{j}}"
            [(ngModel)]="helper[i][j].value" (ngModelChange)="onValueChange(f,i)"/>
      </td>
    {{item}}
    </tr>
</table>

And my CSS is

table.forth.td:nth-child(2){background-color: green}
table.forth.td:nth-child(5){background-color: green}


table.before_forth.td:nth-child(2){background-color: red}
table.before_forth.td:nth-child(5){background-color: red}

So, what I would like to do is to set the colour, which depends on the number of page (in my component I use this method

this.pageNumber = this.activatedRoute.snapshot.queryParams['page'];

and it worked fine in other cases ( I use it oft)

I guess the problem is in css, in this piece of code table.forth.td:nth-child, could you please tell me what would be the right way to access class within the table?

Upvotes: 1

Views: 2356

Answers (1)

Poul Kruijt
Poul Kruijt

Reputation: 71921

You should use pageNumber === 4 and not pageNumber = 4, because then you are just assigning the variable:

<table [ngClass]="{'before_forth': pageNumber < 4, 'forth': pageNumber === 4}">

The second problem is the css rule, you are using a .td class in there, even though it's nowhere used in the html. My guess is that you want to target the <td> element inside the table:

table.forth td:nth-child(2){background-color: green}
table.forth td:nth-child(5){background-color: green}


table.before_forth td:nth-child(2){background-color: red}
table.before_forth td:nth-child(5){background-color: red}

The third problem is the usage of {{item}} outside the <td> tag. This is invalid html and will result in unwanted behaviour, you should move this inside the td

Also, don't use id inside in combination with *ngFor. An element with an id is supposed to be unique throughout the entire page. Actually, it's better not to use id at all if you have no special use for it:

<table [class.before_forth]="pageNumber < 4" [class.forth]="pageNumber === 4">
  <tr *ngFor="let item of itemsSource3; let i = index;">
    <td *ngFor="let item2 of helper[i]; let j = index;">
      <input class="resizedTextbox" name="{{i}}{{j}}" [(ngModel)]="helper[i}[j].value" (ngModelChange)="onValueChange(f,i)">
      {{item}}
    </td>
  </tr>
</table>

The last point is, the proper spelling of 4th is fourth and not forth, but that's just an fyi ;)

Upvotes: 2

Related Questions