angular - 何时显示未定义变量时出现错误
问题描述
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中的代码
解决方案
由于您将其定义为未定义,因此它将首先是未定义的,以便处理未定义的错误。使用安全导航运算符如下,
<p>id: {{ bellowContent?.id }}</p>
<p>first: {{ bellowContent?.first }}</p>
<p>first: {{ bellowContent?.last }}</p>
<p>first: {{ bellowContent?.title }}</p>
将 bellowContent 初始化为 Empty 对象的正确方法
bellowContent = {};
推荐阅读
- python - 如何更改熊猫箱线图中的y标签步骤
- python - 使用 Pandas DataFrame 连续计算过去间隔的平均值
- d3.js - 如何使用 d3 自定义符号创建药丸矩形
- r - 如何在将多个图排列在一起时修改我的图例以不使用 ggplot2 折叠图
- javascript - 如何控制鼠标滚动事件,然后在 html、body 上制作动画?
- html - 如何为选择标签中的所有选项添加图像?
- angular - ng-serve 加载太慢
- arrays - 不同大小数组(锯齿状数组)的 Python 集合,Dask?
- typescript - 如何向应用程序添加动态标题 - VueJS
- java - 如何删除 java.io.IOException:流已关闭?