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));
}
}
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}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With