Reputation: 565
I got error Error: _co.bellowContent is undefined
when to display data. You can refer my code bellow.
I got error Error: _co.bellowContent is undefined
when to display data. You can refer my code 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>
And
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
}
}
This is my code in stackBlitz
Upvotes: 3
Views: 259
Reputation: 15423
Initialize bellowContent
to an empty object {}
rather than undefined
:
bellowContent = {};
On further study of your code, it seems that it may not be desirable to display the labels id, first,etc until and unless the user clicks on one of the rows. In that case, you can just wrap the content you want to display using
<div *ngIf="bellowContent">
...
</div>
and keep your initial initialization of bellowContent to bellowContent:undefined
Upvotes: 1
Reputation: 222582
Since you are defining it as undefined, it will be undefined in the first place, inorder to handle the undefined error. Use Safe Navigation operator as follows,
<p>id: {{ bellowContent?.id }}</p>
<p>first: {{ bellowContent?.first }}</p>
<p>first: {{ bellowContent?.last }}</p>
<p>first: {{ bellowContent?.title }}</p>
Also proper way to initialize the bellowContent as an Empty object
bellowContent = {};
Upvotes: 1
Reputation: 21638
Use an ngIf on the content trying to access properties on an undefined object. It looks cleaner than having the safe navigation operator everywhere.
<div *ngIf="bellowContent">
<p>id: {{ bellowContent.id }}</p>
<p>first: {{ bellowContent.first }}</p>
<p>last: {{ bellowContent.last }}</p>
<p>title: {{ bellowContent.title }}</p>
</div>
Upvotes: 1
Reputation: 1022
Dont't keep undefined as type, put *ngIf condition to the div
Modified code https://stackblitz.com/edit/angular-zftsyc?file=src/app/app.component.html
Upvotes: 1