c0micrage
c0micrage

Reputation: 1180

Angular ngIF is not working with my object property to apply a condition to show and hide

I am writing a condition with the *ngIf in my HTML code. I have a object which contains a property to show and hide a mat-list-item.

Here is the code

<mat-list-item  *ngIf="object.conditionName" 
 [ngClass]="((object.show) || i%2 != 0) ? 'myCssColor' : 'odd'">

In my ts code

public showDetails: boolean = false;

object: [{ name: 'MyName', conditionName: 'showDetails'}];

I did a test and set the *ngIf to conditionName which is showDetail but the UI is displaying the row in the mat-list-item. basically it did not work and could not read the false.

If I did this

*ngIf="showDetails". This works and the UI is not showing the row.

also *ngIf="false" works too.

In each of my table row, there is a different ngIf condition name like showDetail1, showDetail2, etc...

I need to read the object and it property which are the names of my ts class booleans.

I am not sure why *ngIf="object.conditionName " is not work or cannot read.

Also,

if the *ngIf="object.conditionName " , on my VS Code, the intellisense cannot see the object property but it can list all the properties inside the ngClass.

Any help is appreciated. Thanks.

Upvotes: 1

Views: 2254

Answers (3)

Ancy Anto
Ancy Anto

Reputation: 1

As said in the above reply, it's not checking whether it is truthy or not, rather than that you need to provide the actual condition.

For me this worked.

<mat-list-item *ngIf="value === true">

Upvotes: 0

John Montgomery
John Montgomery

Reputation: 7096

I think you're misunderstanding how *ngIf works in this situation. You aren't looking at the showDetails property on the component, you're just checking whether the string "showDetails" is truthy, which of course it is.

If you want it to point to a property on the component, you have to specifically tell it to do that, like this: *ngIf="this[object.conditionName]"

Upvotes: 4

c0micrage
c0micrage

Reputation: 1180

I had to use this to get it to work

*ngIf="this[obejct.conditionName]"

Upvotes: 0

Related Questions