首页 > 解决方案 > 何时显示未定义变量时出现错误

问题描述

Error: _co.bellowContent is undefined 显示数据时出现错误。你可以参考下面我的代码。Error: _co.bellowContent is undefined 显示数据时出现错误。你可以参考下面我的代码。

app.component.html

<table class="table">
  <thead>
    <tr>
      <th scope="col">#</th>
      <th scope="col">First</th>
      <th scope="col">Last</th>
      <th scope="col">Title</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let tableRow of table" (click)="open(tableRow)">
      <th scope="row">{{tableRow.id}}</th>
      <td>{{tableRow.first}}</td>
      <td>{{tableRow.last}}</td>
      <td>{{tableRow.title}}</td>
    </tr>
  </tbody>
</table>

<div>
<p>id: {{ bellowContent.id }}</p>
<p>first: {{ bellowContent.first }}</p>
<p>last: {{ bellowContent.last }}</p>
<p>title: {{ bellowContent.title }}</p>
</div>

app.component.ts

  bellowContent:undefined
  table = [
  {
    "id": 1,
    "first":"Robin",
    "last": "William",
    "title": "back end developer"
  },{
    "id": 2,
    "first":"Mark",
    "last": "Thornton",
    "title": "front end developer"
  },{
    "id": 3,
    "first":"Tary",
    "last": "Huction",
    "title": "front end developer"
  }
]


  open(tableRow) {
      this.bellowContent = tableRow
  }
}

这是我在stackBlitz中的代码

标签: angulartypescript

解决方案


由于您将其定义为未定义,因此它将首先是未定义的,以便处理未定义的错误。使用安全导航运算符如下,

<p>id: {{ bellowContent?.id }}</p>
<p>first: {{ bellowContent?.first }}</p>
<p>first: {{ bellowContent?.last }}</p>
<p>first: {{ bellowContent?.title }}</p>

将 bellowContent 初始化为 Empty 对象的正确方法

 bellowContent = {};

STACKBLITZ DEMO


推荐阅读