5

I am trying to print a value in the template of component.

But I am getting the above error Cannot read property 'name' of undefined

I have removed the extra contents from code for this question. I want to access the first row of the details.

Components file

import {
  Component
} from '@angular/core';
import {
  Person
} from './person';
import {
  getPersonDetailsService
} from './person.service';

@Component({
  selector: 'my-app',
  template: `
      {{data[0].name}}
      `
})
export class AppComponent {
  data: Person[] = [];
  ngOnInit(): void {
    this.getPersonDetailsService.getData()
      .then(data => this.data = data.slice(1, 5));
  }

}
eko
  • 39,722
  • 10
  • 72
  • 98
Netdeamon
  • 175
  • 2
  • 3
  • 9

4 Answers4

22

I think you should first check if data is defined when you print it in browser.

{{data[0]?.name}}

As your data is not defined initially, you cannot access the name property of it.

Documentation

The Angular safe navigation operator (?.) is a fluent and convenient way to guard against null and undefined values in property paths. Here it is, protecting against a view render failure if the currentHero is null.

You can also check if the variable is null or not by using && condition

{{data[0] && data[0].name}}

Santosh
  • 1,871
  • 1
  • 19
  • 36
0

From your error message, it seems like data is undefined (or is empty) - and the error is happening on the line that says

{{data[0].name}}

Maybe put in a console.log(data) before then to verify what is going on

Yaakov Ellis
  • 40,752
  • 27
  • 129
  • 174
0

Try put this into constructor instead of ngOnInit:

getPersonDetailsService.getData() ...

Also, you need to make some check inside template in case that 'data' does not have length > 0 {{data[0]?.name}}

Nedim Hozić
  • 1,871
  • 15
  • 15
0

The value for the "data" is getting updated after response is resolved from your getData() service. I am assuming you are hitting a service and getting the data. Nevertheless, the promise would be resolved once the service returns the response. The View meanwhile tries to render the template and as it evaluates the expression data[0], its doesn't find any element at 0 as the data has not still arrived from the service. Hence you get the error as the element at 0th index is undefined.

You should be using an observable here.

Sundar
  • 41
  • 7