0

Normally I use *ngIf if I want to exclude something from my *ngFor loop.

However in this case I can't.

.HTML

<div class="grid">
    <div  *ngFor="let food of foods | async " >
        <ion-card *ngIf="food.data.name !=''">

           {{food.data.name}}

        </ion-card>
    </div>
<div>

this is an overly simplified version of the code.

I'm doing a grid pattern of each row having two <ion-card>.

I'm trying to skip over the elements in the array that have a blank name "".

Since this is an async loop, at any moment those "" names could hold real values and will automatically update the grid.

However, using *ngIf is leaving blank spaces in the grid instead of skipping over those areas that have a "" name.

I heard there are ways of using pipes for *ngFor for passing over arguments.

I haven't managed to get any to work.

I am on Ionic 6.10.1

win4win
  • 323
  • 6
  • 20
  • 1
    I would recommend filtering those values out in the component and let the template handle just displaying the data. – Phix Aug 11 '20 at 18:48
  • 1
    I think you should follow this question's answer: https://stackoverflow.com/questions/34164413/how-to-apply-filters-to-ngfor – BenceL Aug 11 '20 at 18:48
  • 1
    This is considered a bad practice in MVC / MVVM architecture. Your templates should only be used to show data as much as possible. I would highly suggest you do the necessary logic in your code behind (eg. component ts) and then passed the filtered data to your template file. This way, it's not only faster to render but it helps you better debug your application. – Raven Aug 11 '20 at 18:49
  • It's just that an external source will be updating these variables from somewhere else. If we filter out the empty variables out the array in the script, they could be updated and since they were removed, they won't be displayed in the HTML. This is not something I would normally do however. – win4win Aug 11 '20 at 19:02

1 Answers1

2

Because your ngIf is inside your « div *ngFor » you’ll always have an empty div despite the fact that the string is empty. You should use a pipe for filtering value at the same level that *ngFor

@Pipe({name: 'filterEmpty'})
export class filterEmpty implements PipeTransform {
  transform(value: any[],...args:any): string {
   return value.filter(v => v.data.name !== ‘’); // or whatever filter you want
  }
}

And in your code :

<div *ngFor="let food of foods | async | filterEmpty">
cyberbobjr
  • 239
  • 2
  • 6
  • It worked! After `transform(value: any[],...args:any): any {` I had to add `if (value==null) {return null;}` because it was an async function. – win4win Aug 12 '20 at 14:42