Jestzy
Jestzy

Reputation: 1

How to check if element exists in an Object?

How to use *ngIf to check if an element exists in an Object?

.ts file

this.data = ["cat", "dog"];

I want to check, in my html file, if cat exists in the object this.data or not. Can I do that with an *ngIf ?

Upvotes: 0

Views: 1092

Answers (3)

Arjun
Arjun

Reputation: 1342

You can use ngFor first to iterate every element in a loop and then use ngIf to check if value exist or not.

for example:

<div *ngFor="let element of data">
    <div *ngIf="element.cat">
     </div>
</div>

Another method is make seperate function for this but I think this is easy way to do.I hope it will help you.:)

Upvotes: 0

Ichraf
Ichraf

Reputation: 355

you can create a function in your ts file to check if the wanted string exists in the array or not like this :

doesExist(animal: string): boolean {
return this.data.includes(animal);
}

and then call it in your html file :

<div *ngIf="doesExist('cat')"> [...] </div>

Upvotes: 1

VISHAL SINGH
VISHAL SINGH

Reputation: 661

<div *ngIf="data.includes('cat')">hello world</div>

I hope this will help.

Upvotes: 0

Related Questions