简体   繁体   中英

ngFor in Angular making 5 divs and 5 uls -- instead of inside items

The question is surprising behavior of ngFor and loopings items generated inside it.

I am making a simple example to refer *ngFor in Angular4/5/6. The issue is that I was expecting 1 div to contain 5 paragraph. I am amazed to see that I am getting instead 5 divs each containing 1 paragraph. Why is this and how to fix this? I am surprised same is happening for ul-li items also !!! -- strange.

abc.component.html

 <div *ngFor="let x of students">
   <p>{{x.name}}, {{x.age}}, {{x.country}}, {{x.gender}}</p>
 </div>

abc.component.ts

  students = [
    {name: "Jack", age: 29, gender:"male", country: "USA"},
    {name: "Ronald", age: 33, gender: "male", country: "UK"},
    {name: "Lisa", age: 19, gender: "female", country: "UK"},
    {name: "Donald", age: 43, gender: "male", country: "Austrailia"},
    {name: "Simera", age: 23, gender: "female", country: "Italy"}
  ];

abc.component.css

div{border:1px solid black;}

在此处输入图片说明

Even for ul-li (I am getting ul generated 5 times containing 1 li item in each)

<ul *ngFor="let x of students">
  <li>{{x.name}}, {{x.age}}</li>
</ul>

在此处输入图片说明

Put your ngFor on <p> tag instead of <div> which will create 5 paragraph in one div.Like following:

<div>
   <p *ngFor="let x of students">{{x.name}}, {{x.age}}, {{x.country}}, {{x.gender}}</p>
 </div>

You need to put *ngFor inside paragraph tag

<div>
   <p *ngFor="let x of students">
      {{x.name + ', ' + x.age + ', '+ x.country + ', '+ x.gender}}
   </p>
</div>

Please review carefully 2 code snipped:

//1

 <div *ngFor="let x of students">
   <p>{{x.name}}, {{x.age}}, {{x.country}}, {{x.gender}}</p>
 </div>

//2

<ul ngFor="let x of students>
  <li>{{x.name}}, {{x.age}}</li>
</ul>

In 1: You wrote: *ngFor="..."

In 1: You wrote: ngFor="..." You must rewrite to: *ngFor="..."

Hope to helpful!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM