鍍金池/ 問(wèn)答/HTML5  HTML/ Cannot read property 'XXX' of undefined

Cannot read property 'XXX' of undefined

angular2里,在ts中取出后臺(tái)封裝的對(duì)象數(shù)組([Object,Object...]),在html中,直接引用對(duì)象的屬性(Object.XXX)就會(huì)報(bào)錯(cuò)“Cannot read property 'XXX' of undefined”,但是頁(yè)面又已經(jīng)顯示出了XXX。但是用ngFor遍歷出對(duì)象集合,再引用其中一個(gè)對(duì)象的XXX屬性,就不會(huì)報(bào)錯(cuò)。這怎么解決呢

顯示但報(bào)錯(cuò):

      {{questions[currentNo].content}}

正常:

      <ng-container *ngFor="let qsn of questions ;index as qNo" >
        <div class="qsnHost" *ngIf="qNo==currentNo">
          {{qsn.content}}
        </div>
      </ng-container>
     
回答
編輯回答
陌上花

{{qsn?.content}}

<div *ngIf="qsn">
<div class="qsnHost" *ngIf="qNo==currentNo">

  {{qsn.content}}

</div>
</div>

2018年4月14日 18:39