philip yoo
philip yoo

Reputation: 2512

Using *ngFor to loop through an array and *ngIf to select which elements from the array to list

I'm trying to use *ngFor to loop through an array of objects. I realized I couldn't use *ngFor and an *ngIf on the same element, it would return an error. Instead, I tried to stick my *ngIf on the contents of the list item. But now, I'm getting a bunch of empty list items and they're being created and displayed on my view page.

I don't want to stick the *ngFor on my <ul> element because then it will create a bunch of <ul> elements with a single list item within each.

I'm hoping one of you will have another method of implementing this.

// AppComponent
// contacts: Contact[];  // An array of `Contact` Objects

<ul>
  <li *ngFor="#contact of contacts">
    <contact-detail *ngIf="checkList(contact) == true" [contact]="contact"></contact-detail>
  </li>
</ul>

and...

// ContactDetailComponent
<img />
<span>{{contact.name}}</span>
<span>{{contact.email}}</span>

What is happening:

<ul>
  <li>
    <!--template bindings={}-->  // ngIf conditional returned true
    <img />
    <span>Name1</span>
    <span>Email1</span>
  </li>
  <li>
    <!--template bindings={}-->   // ngIf conditional returned false
  </li>
  <li>
    <!--template bindings={}-->  // false
  </li>
  <li>
    <!--template bindings={}-->  // true
    <img />
    <span>Name1</span>
    <span>Email1</span>
  </li>
</ul>

I'm using Material Design Lite, so all these elements will have some css properties. Empty <li> just return an empty space of a certain height.

Also, if other information is needed, please let me know.

Upvotes: 5

Views: 21188

Answers (2)

Sasxa's answer didn't work for me at 2022. You can use ng-template instead of template to get the same result.

<ul>
    <ng-template ngFor let-item [ngForOf]="calcService.myDataArray">
        <li *ngIf="item.esTarifa === true">
            {{item.id}}
        </li>
    </ng-template>
</ul>

Upvotes: -1

Sasxa
Sasxa

Reputation: 41264

Both *ngFor and *ngIf (with asterisk) are structural directives and they generate <template> tag:

Structural directives, like ngIf, do their magic by using the HTML 5 template tag.

You can get functionality you want with this syntax:

<ul>
  <template ngFor #contact [ngForOf]="contacts">
    <li *ngIf="checkList(contact) == true" >
      <contact-detail [contact]="contact"></contact-detail>
    </li>
  </template>
</ul>

example: http://plnkr.co/edit/JeDbVi4pXrzJ5SRIonjH?p=preview

Upvotes: 13

Related Questions