【问题标题】:ngFor in Angular making 5 divs and 5 uls -- instead of inside itemsngFor 在 Angular 中制作 5 个 div 和 5 个 uls——而不是内部项目
【发布时间】:2019-03-05 03:22:29
【问题描述】:

问题是 ngFor 的令人惊讶的行为以及在其中生成的循环项。

我正在做一个简单的例子来引用 Angular4/5/6 中的 *ngFor。问题是我期望 1 个 div 包含 5 个段落。我很惊讶地看到我得到了 5 个 div,每个 div 包含 1 个段落。为什么会这样以及如何解决这个问题?我很惊讶 ul-li 物品也发生了同样的情况!!! -- 奇怪。

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;}

即使对于 ul-li(我生成 ul 5 次,每次包含 1 li 项)

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

【问题讨论】:

  • 你需要循环段落标签而不是div标签
  • 行为有区别吗?您实际上并没有显示第二个示例的输出,这不是完全正确的语法;如果编写正确,我希望看到五个 UL,每个都包含一个 LI。
  • 也许你应该了解一下 Angular 的基础知识,它和 AngularJS 不一样:angular.io/tutorial
  • @Deadpool:不,如果用户执行连续投票以“撤消”此操作(可能在 24-48 小时内),StackOverflow 有一些机制到位。如果您怀疑有人给予“不应有的”选票(赞成和反对),您也可以举报。
  • 您首先询问的是两个看起来相同但行为不同的事物的令人惊讶的行为,这确实令人惊讶,只是它们实际上并没有不同的行为。现在你问的是两个看起来相同表现相同的事物的令人惊讶的行为,这……似乎一点也不奇怪。两者都不是一个特别有用的问题。代码的行为与记录一致。

标签: javascript angular dom angular-directive ngfor


【解决方案1】:

将您的ngFor 放在&lt;p&gt; 标签上,而不是&lt;div&gt;,这将在一个div 中创建5 个段落。如下所示:

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

【讨论】:

    【解决方案2】:

    你需要把 *ngFor 放在段落标签内

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

    【讨论】:

      【解决方案3】:

      请仔细检查 2 段代码:

      //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>
      

      在 1 中:您写道:*ngFor="..."

      在 1 中:您写道:ngFor="..." 您必须重写为:*ngFor="..."

      希望对您有所帮助!

      【讨论】:

        猜你喜欢
        • 2019-02-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-03-31
        • 1970-01-01
        • 2019-03-09
        相关资源
        最近更新 更多