Reputation: 11
I have an array with objects, each having a type. I want to display only the objects with a specific type that i change by pressing some buttons. For some reasons, for the "Food" type, it also renders the other two objects but without any content.
Here's the array and type
objects = [
{
title: 'Spartan Sandwich',
price: 4,
type: 'Food',
},
{
title: 'Math Lessons',
price: 10,
type: 'Necesities',
},
{
title: 'Ice Skating',
price: 10,
type: 'Misc',
},
];
type: string = 'Food';
Here's the HTML
<div class="objects">
<div class="object-container" *ngFor="let object of objects">
<app-object [object]="object" *ngIf="object.type === type"></app-object>
</div>
</div>
I know that it's normal for it to always render all the object-container divs, but how can i fix it so that they do not appear?
Upvotes: 0
Views: 1382
Reputation: 537
The best way to do this is by putting the app-object
component inside a virtual container like ng-container
that way there will not be any need to use an extra div.
The code will look like this: `
<div class="objects">
<div class="object-container" *ngFor="let object of objects">
<ng-container *ngIf="object.type === type">
<app-object [object]="object"></app-object>
</ng-container>
</div>
</div>
`
Upvotes: 1
Reputation: 1044
Either you go with the code suggested by Shuvo or you manipulate the "objects" array using filter.
viewData = this.objects.filter(({ type }) => type === this.type);
Upvotes: 1
Reputation: 1293
You can run the ngFor
loop in ng-content
and check the object.type
in object-container
div:
<div class="objects">
<ng-content *ngFor="let object of objects">
<div class="object-container" *ngIf="object.type === type">
<app-object [object]="object"></app-object>
</div>
</ng-content>
</div>
Note: ng-content
doesn't render any HTML
element.
Upvotes: 1