I got error with undefined variable when to display

Viewed 216

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

4 Answers

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 = {};

STACKBLITZ DEMO

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

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>
Related