i何时显示错误 Error: _co.bellowContent is undefined
。您可以引用我的代码bellow。我何时显示错误Error: _co.bellowContent is undefined
。您可以引用我的代码bellow。
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
不将不确定的类型保持不确定,将 *ngif条件放在div
修改的代码https://stackblitz.com/edit/angular-zftsyc?file=src/app/app/app.component.html
在内容上使用NGIF尝试访问未定义对象上的属性。它看起来比到处都是安全导航操作员更干净。
<div *ngIf="bellowContent">
<p>id: {{ bellowContent.id }}</p>
<p>first: {{ bellowContent.first }}</p>
<p>last: {{ bellowContent.last }}</p>
<p>title: {{ bellowContent.title }}</p>
</div>
将bellowContent
初始化为空对象{}
而不是undefined
:
bellowContent = {};
在进一步研究您的代码时,似乎不希望显示标签ID,首先等,除非用户单击其中一个行。在这种情况下,您只需包装要使用
显示的内容<div *ngIf="bellowContent">
...
</div>
并保留您的初始初始化 bellowContent:undefined