Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

*ngFor shows element in empty array

Following *ngFor

<ul>
  <li *ngFor="#todo of todoService.todos">
    {{todo}}
  <li>
</ul>

Where todoService is an Injected Interface

import {Injectable} from 'angular2/core';

@Injectable()
export class TodoService {
    todos = []
}

When I load the page, the output is <li></li> instead of nothing.

Any idea why? Since the array is empty, there shouldn't be a <li>-tag

EDIT It's also occuring when I initialize the array with values. There is always a trailing empty element for no reason.

EDIT2 Example of the problem https://plnkr.co/edit/MRYC4MHtlDLfBMUPsL6o?p=preview

like image 565
Michael Brenndoerfer Avatar asked Jan 30 '16 18:01

Michael Brenndoerfer


People also ask

How do you find the empty element in an array?

To check if an array is empty or not, you can use the .length property. The length property sets or returns the number of elements in an array. By knowing the number of elements in the array, you can tell if it is empty or not. An empty array will have 0 elements inside of it.

What is * in ngFor angular?

*ngFor is a predefined directive in Angular. It accepts an array to iterate data over atemplate to replicate the template with different data. It's the same as the forEach() method in JavaScript, which also iterates over an array.

Can you have 2 ngFor?

So you cannot use two ngFor s on the same element, but you can use the index, if both arrays are of the same size, to check whether or not there is a value.

Can we use ngFor in UL tag?

Angular2: <li> with *ngFor not inside <ul> The <ul> tag is not filled by those <li> tag created by *ngFor which makes the "line" of the timeline disappear. The black border is the border of the <ul> tag, which is suppose to wrap all <li> tags below it and have the magenta line go through all bubbles.


1 Answers

Ah yes :) you can stare blind at problems like these, even though the solution is sometimes too simple.

I believe you would like the bottom <li> to be a closing tag? That might just fix your issue:

<ul>
  <li *ngFor="#todo of todoService.todos">
    {{todo}}
  </li>  <!-- this nagger right here -->
</ul>
like image 84
Poul Kruijt Avatar answered Oct 17 '22 00:10

Poul Kruijt