Faigjaz Faigjaz - 1 month ago 30
TypeScript Question

Angular 2 - *ngFor with conditional class

I am using Angular2 and bootstrap for a component.
I am trying to add a class to my tr-tag if the property "2" of the test from the *ngFor loop is equal to an imported variable named newTest.
But it's not adding the class.

Here's my component:

loadTest() {
this.testService.getTests()
.then((data) => {
this.tests = data
})
}

ngOnInit() {
this.loadTest();
}


The table is displayed correctly, but the class isn't there.

The condition definitely is fullfilled, though.

Here's my html:

<div class="table-responsive">
<table class="table table-hover table-reflow">
<thead>
<tr>
<th>1</th>
<th>2</th>
<th>3</th>
<th>4</th>
<th>5</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let test of tests" [class.newDevice]="test.2 === this.newTest" [attr.class]="test.1" >
<th>{{test.1}}</th>
<th>{{test.2}}</th>
<th>{{test.3}}</th>
<th>{{test.4}}</th>
<th>{{test.5}}</th>
</tr>
</tbody>
</table>
</div>


Am I doing something else wrong?
I've tried achieving the same with jquery, too:

loadTest() {
this.testService.getTests()
.then((data) => {
this.tests = data
if (NewTest.length !== undefined) {
let index = this.tests.findIndex((e) => { return e.2 === NewTest })
let test = this.tests[index].id
jQuery(test).addClass("newDevice");
}
})
)

Answer

[class.newDevice] and [attr.class] are overriding each other.

Comments