首页 > 解决方案 > 页面显示为空,而组件有许多元素要显示在屏幕上

问题描述

我们试图将数据对象中的内容放在行和列中。但是,当我们检查错误时,屏幕显示为空,并且在控制台上显示未捕获的错误,但我们很困惑地弄清楚哪些行是完全错误的以及如何修复它们。类型脚本部分没问题。似乎所有错误都在组件的 HTML 部分中。这是代码:

<div class="container justify-content-center">
<div class="row row row-centered justify-content-center" *ngFor="let restaurant of restaurants; let i = index" *ngIf="i % 3 == 0">
      <div class="col-md-3 centered col-md-offset-1">
        <span>
        <img
          [src]="restaurant.imagePath"
          alt="{{ restaurant.name }}"
          class="img-responsive"
          style="max-height: 300px; width:100%;">
      </span>
          <h2>{{restaurant.name}} </h2>
          <h2>{{restaurant.category}} </h2>
          <p>{{restaurant.description}} </p>
         </div>
        <div class="col-md-3 centered col-md-offset-1">
        <span>
        <img *ngIf="restaurants[$index + 1].imagePath != null" [src]="restaurant[i +
              1].imagePath"
          class="img-responsive"
          style="max-height: 300px; width:100%;">
      </span>
          <h2 *ngIf="restaurants[$index + 1].name != null">{{restaurants[i +
              1].name}} </h2>
          <h2*ngIf="restaurants[$index + 1].category != null">{{restaurants[i +
              1].category}} </h2>
              <p *ngIf="restaurants[$index + 1].description != null">{{restaurants[i +
              1].description}} </p>

      </div>
         <div class="col-md-3 centered col-md-offset-1">
        <span>
        <img *ngIf="restaurants[$index + 2].imagePath != null" [src]="restaurant[i +
              2].imagePath"
          class="img-responsive"
          style="max-height: 300px; width:100%;">
      </span>
          <h2*ngIf="restaurants[$index + 2].name != null">{{restaurants[i +
              2].name}} </h2>
          <h2*ngIf="restaurants[$index + 2].category != null">{{restaurants[i +
              2].category}} </h2>
              <p *ngIf="restaurants[$index + 2].description != null">{{restaurants[i +
              2].description}} </p>
                       </div>
      </div>

  </div>
</div>

怎么了?我们如何修复这些错误并使其在浏览器上显示组件?

标签: angular

解决方案


在您的 HTML 模板中,您在同一元素上使用了 ngForngIf,但根据角度文档,每个宿主元素只能使用一个结构指令

您可以按照ngFor 语法使用以下语法,并在ng-template内的 div 上 使用ngIf

<ng-template ngFor let-item [ngForOf]="items" let-i="index" [ngForTrackBy]="trackByFn">
  <div>...</div>
</ng-template>

对于列基础布局,您可以为列创建一个组件并将您的餐厅数据作为输入传递给它。在您的 html 中使用此新组件三次,如下所示:

// Component
public items = new Array(Math.round(this.restaurents.length/3));

//Template

<ng-template ngFor let-item [ngForOf]="items" let-i="index" [ngForTrackBy]="trackByFn">
  <my-col [data]="itmes[i*3]" ngIf="itmes[i*3]">...</my-col>
  <my-col [data]="itmes[i*3 + 1]" ngIf="itmes[i*3 + 1]">...</my-col>
  <my-col [data]="itmes[i*3 + 2]" ngIf="itmes[i*3 + 2]">...</my-col>
</ng-template>

推荐阅读