angular - 当显示时出现 undefined variable 错误

标签 angular typescript

我在显示数据时遇到错误错误:_co.bellowContent未定义。你可以引用我下面的代码。 显示数据时出现错误 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 中的代码

最佳答案

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

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

也是将波纹管内容初始化为空对象的正确方法

 bellowContent = {};

STACKBLITZ DEMO

关于angular - 当显示时出现 undefined variable 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56746816/

相关文章:

angular - 如何使用 ContentChildren 和 QueryList 重新排序子项

Angular - 具有 asp.net core spa 的多环境

javascript - 发布 TypeScript React 组件时有关 TS 类型的问题

reactjs - React TypeScript 包含父级将 prop 传递给子级

arrays - 我将一个数组传递给 'xlsx' 以获取一个 Excel 文件,但我得到了在每一行中解析的数组元素

TypeScript 嵌套异步函数

angular - JSONP 注入(inject)脚本没有调用回调

angular - 我们可以使用 HTTP 2 服务器推送存在于其他 CDN 中的 Assets 吗?

angular - OPTIONS 请求的 CORS 问题

javascript - 如何在此函数中提供 Observable?