ERROR TypeError:无法读取属性' news_category'未定义的

时间:2018-05-25 06:47:46

标签: angular ionic-framework ionic3

HTML

<ion-content>
    <p>{{volunteer.news_category}}</p>

  <ion-grid>
    <ion-row>
      <ion-col>
        <ion-card tappable (click)="goToVolunteerVoteDetail(volunteer)" style="width:26%" class="pin" 
          *ngFor="let volunteer of selectedVolunteer">
          <!-- <p>{{volunteer.news_category}}</p> -->

          <img src="{{volunteer.Preview_image1}}" height="100">
          <div *ngIf="volunteer.title" class="volunteer-title">
            <small>{{volunteer.title}}</small>
          </div>
          <div class="volunteer-title">{{volunteer.like_number}}分</div> <!-- 志愿者评选头像像素:505x505px -->

        </ion-card>
      </ion-col>
    </ion-row>
  </ion-grid>
</ion-content>

它将显示以下错误:

  

错误类型错误:无法读取属性&#39; news_category&#39;未定义的

但如果我将<p{{volunteer.news_category}}</p>更改为

<div *ngFor="let volunteer of selectedVolunteer">
   <p>{{volunteer.news_category}}</p>
</div>

错误将消失,但会显示许多 news_category

我只希望它只显示一次。

1 个答案:

答案 0 :(得分:0)

由于selectedVolunteer的所有项目保持news_category的相同值,您只需显示第一项news_category,并根据selectedVolunteer的长度显示/隐藏它。

<div *ngIf="selectedVolunteer?.length > 0">
  <p>{{selectedVolunteer[0].news_category}}</p>
</div>