Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check for "Not in" a list condition Angular 2 template

Tags:

html

list

angular

I have a template as below:

<span *ngIf="item.status !=='E1' && item.status !=='B' && item.status !=='R'">{{item.status_desc}}</span>

As above, i have a ngIf condition there, making no sense but somehow it working. What am trying to do there is check "status in [E1, B, R]" something like that. How can i do that in the html without going to the ts file. Any idea guys?

like image 546
blackdaemon Avatar asked Feb 26 '26 23:02

blackdaemon


2 Answers

If you really don't want to go to your TypeScript source, you can do something like this for increased readability.

<span *ngIf="!['E1', 'B', 'R'].includes(item.status)">{{item.status_desc}}</span>

But perhaps it's wiser to make a variable on your class with the 'undesired' statuses like:

public ignoreStatus: string[] = ['E1', 'B', 'R'];

and then

<span *ngIf="!ignoreStatus.includes(item.status)">{{item.status_desc}}</span>

but then it would be even better to make a reusable method out of this in your class:

public isIgnoreStatus(item: any): boolean {
    return this.ignoreStatus.includes(item.status);
}

with

<span *ngIf="!isIgnoreStatus(item.status)">{{item.status_desc}}</span>
like image 81
Poul Kruijt Avatar answered Feb 28 '26 13:02

Poul Kruijt


In your HTML, you could use includes(), which returns true if the element is found:

<span *ngIf="!['E1', 'B', 'R'].includes(item.status)">{{item.status_desc}}</span>

as JB Nizet suggested.


Or you could use a function, like this:

statusList = [E1, B, R];
checkStatus(item)
{
  return (statusList.indexOf(item) != -1);
}

where your HTML now should llol like this:

<span *ngif="checkStatus(item.status)">{{item.status_desc}}</span>
like image 43
gsamaras Avatar answered Feb 28 '26 13:02

gsamaras