Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

angular

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.

like image 228
philip yoo Avatar asked Mar 04 '16 00:03

philip yoo


People also ask

Can we use ngIf and * ngFor together?

Use ngFor and ngIf on same element It's very common scenario where we want to repeat a block of HTML using ngFor only when a particular condition is true. i.e., if ngIf is true.So in this case to use *ngIf and *ngFor on same element, place the *ngIf on a parent element that wraps the *ngFor element.

What is the difference between ngFor and ngIf?

NgIf conditionally displays items by adding or removing them from the DOM depending on the condition. NgFor renders a list of items from iterable objects.


1 Answers

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

like image 137
Sasxa Avatar answered Oct 15 '22 07:10

Sasxa