Home > Blockchain >  Angular - change class name
Angular - change class name

Time:01-06

I use the ngClass to change the class name to either odd or even.

<ng-container
    matColumnDef="{{ column }}"
    *ngFor="let column of keys; let o = odd; let e = even"
    [ngClass]="{ odd: o, even: e }"
  >

and I get the following error: "core.mjs:6495 ERROR TypeError: Cannot read properties of undefined (reading 'remove') at EmulatedEncapsulationDomRenderer2.removeClass"

Could you help me, please? Thanks in advance.

CodePudding user response:

You are creating a local variable like this let o = odd; let e = even. As I know you have only access to index, you would write something like this let i = index.

All in all, odd and even are null. They don't exist. You could make this work by removing those 2 local variables. After that you could dynamically assing class to this element using this expression:

[ngClass]="{ 'odd': column % 2 !== 0; 'even': column % 2 === 0 }"

Also double-check do this css classes exist in your component .css file.

CodePudding user response:

If you want to add class by index :

<ng-container
  *ngFor="let column of keys; let i = index"
  [ngClass]="i % 2 === 0 ? 'odd' : 'even'"
  [matColumnDef]="column"
></ng-container>

or If you want to add class by column variable

<ng-container
  *ngFor="let column of keys; let i = index"
  [ngClass]="i % 2 === 0 ? 'odd' : 'even'"
  [matColumnDef]="column"
></ng-container>

CodePudding user response:

You are setting class to ng-container which is not rendered. Put the ngClass to child <div> element

<ng-container
    matColumnDef="{{ column }}"
    *ngFor="let column of keys; let o = odd; let e = even">
<div [ngClass]="{ odd: o, even: e }"> ... </div>

This code is fine.

The error come from another place undefined.remove

  •  Tags:  
  • Related