Reputation: 1
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
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
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
Reputation: 661
<div *ngIf="data.includes('cat')">hello world</div>
I hope this will help.
Upvotes: 0