【问题标题】:Error on ngFor only show the second object from arrayngFor 上的错误仅显示数组中的第二个对象
【发布时间】:2021-03-28 07:18:11
【问题描述】:

每个部分应该有两个可编辑的输入字段,并且每个部分都应该有它对应的数据。然而,这两个部分只显示了示例中的第二个 JSON。

TS 文件中的 JSON 如下所示:

this.sample = [
{
"sectionone":"abc",
"sectiontwo":"dec"
},
{
"sectionone":"ncs",
"sectiontwo":"sec"
}];

html 文件

<div ngFor="let x in sample; let i = index">
 <h6>{{i}}</h6>
 <h6>{{sample[i].sectionone}}</h6>
  <div class="A">
  <label>Section ONE</label>
    <div class="one {i}" >
     <input [(ngModel)] = "sample[i].sectionone" />
    </div>
  </div>
  <div class="A">
  <label>Section TWO</label>
    <div class="two {i}" >
     <input [(ngModel)] = "sample[i].sectiontwo" />
    </div>
  </div>
  <br/>
</div>

所以 h6 的结果,我得到 0 abc 和 1 ncs,这是我需要的正确答案,但是,输入部分中的数据显示是第一部分:ncs,第二部分:sec,第一部分: ncs,第二部分:秒。两者都使用示例数组中的第二个 JSON。我不知道哪里出错了。

【问题讨论】:

    标签: javascript html angular typescript angular8


    【解决方案1】:

    你好,你犯了一些小错误, 这是更正

    <div *ngFor="let x of sample; let i = index ">
        <h6>{{i}}</h6>
        <h6>{{x.sectionone}}</h6>
        <div class="A">
            <label>Section ONE</label>
            <div class="one {i}">
                <input [(ngModel)] = "x.sectionone" />
        </div>
            </div>
            <div class="A">
                <label>Section TWO</label>
                <div class="two {i}">
                    <input [(ngModel)] = "x.sectiontwo" />
        </div>
                </div>
                <br/>
    </div>
    

    *ngFor 的语法错误,正确的是 of 而不是 in。 您可以使用let x 代替数组和索引。 这是stackBlitz

    【讨论】:

      猜你喜欢
      • 2016-08-18
      • 2018-08-13
      • 2020-11-29
      • 1970-01-01
      • 2015-02-19
      • 2022-07-07
      • 1970-01-01
      • 2017-07-24
      • 2020-01-22
      相关资源
      最近更新 更多