Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot read property 'name' of undefined angular 4 [duplicate]

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));
  }

}
like image 662
Netdeamon Avatar asked May 21 '17 10:05

Netdeamon


1 Answers

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

like image 66
Santosh Avatar answered Oct 02 '22 01:10

Santosh