Categories
Angular Answers

How to fix Cannot read property ‘name’ of undefined with inputs in Angular?

Spread the love

Sometimes, we want to fix Cannot read property ‘name’ of undefined with Angular.

In this article, we’ll look at how to fix Cannot read property ‘name’ of undefined with Angular.

How to fix Cannot read property ‘name’ of undefined with Angular?

To fix Cannot read property ‘name’ of undefined with Angular, we can use the safe navigation operator.

For instance, we write

<input
  [ngModel]="selectedHero?.name"
  (ngModelChange)="selectedHero.name = $event"
/>

to set [ngModel] to selectedHero?.name.

We use the safe navigation operator (?.) to stop errors from being thrown when selectedHero is null or undefined.

Conclusion

To fix Cannot read property ‘name’ of undefined with Angular, we can use the safe navigation operator.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *