Menu Close

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

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.

Posted in Angular, Angular Answers