【问题标题】:ng for loop into other ng for loop not work Angularng for 循环进入其他 ng for 循环不起作用 Angular
【发布时间】:2021-07-28 15:39:20
【问题描述】:

我想使用 ngFor 将模型数组列表显示到其他 ng for 但我遇到了一系列问题,因为显然我的模型的属性无法从 HTML 中识别。但是发生了非常非常奇怪的事情,希望你能帮助我

我的界面:

export interface ShoppingCar {
  username: string;
  items: ItemShoppingCar[];
}

export interface ItemShoppingCar {
  description: string;
  price: number;
}

我的ts:

export class ShoppingComponent implements OnInit {

  shopItems: ShoppingCar[] = [];

  constructor(private shoppingService: ShoppingService) { }

  ngOnInit(): void {
    this.shoppingService.all()
    .subscribe(
        (response) => {
            if(response.success) {
                this.shopItems = response.Result;
            }
        }
    );
  }
}

我的html:

<div *ngFor="let shopItem of shopItems">
 <div class="card">
    <div class="card-body">
      <h5 class="card-title">{{ shopItem.username }}</h5>
      <hr>
      <div class="flex-items" *ngFor="item of shopItem.items">
        <span class="descripcion-item">{{ item.description }}</span>
        <span class="price-item">{{ item.price }}</span>
      </div>
    </div>
</div>

编译错误

错误 TS2339:“ShoppingComponent”类型上不存在属性“项目”。

56              <span class="descripcion-item">{{ item.description }}</span>

错误 TS2339:“ShoppingComponent”类型上不存在属性“项目”。

56               <span class="price-item">{{ item.price }}</span>

当我使用 ctrl + s 保存我的模型文件时,如果它可以编译,但是在执行它时会引发另一个错误,因为显然它无法识别我的第二个 ngFor 循环的模型的属性。

core.js:10069 NG0303: Can't bind to 'ngFor' since it isn't a known property of 'div'.
logUnknownPropertyError @ core.js:10069
5core.js:6157 ERROR TypeError: Cannot read property 'description' of undefined

【问题讨论】:

    标签: html angular ngfor


    【解决方案1】:

    您似乎在嵌套循环中忘记了let。我觉得应该是*ngFor="letitem of shopItem.items":

    <div *ngFor="let shopItem of shopItems">
     <div class="card">
        <div class="card-body">
          <h5 class="card-title">{{ shopItem.username }}</h5>
          <hr>
          <!-- here we go: -->
          <div class="flex-items" *ngFor="let item of shopItem.items">
            <span class="descripcion-item">{{ item.description }}</span>
            <span class="price-item">{{ item.price }}</span>
          </div>
        </div>
    </div>
    

    这个应该可以解决您的错误。它解释了为什么属性“项目”不存在以及为什么您无法读取项目的属性“描述”。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-10
      • 1970-01-01
      • 2022-11-14
      • 1970-01-01
      • 1970-01-01
      • 2014-04-19
      • 2017-04-13
      • 2013-12-31
      相关资源
      最近更新 更多