[转]Angular2: Cannot read property 'name' of undefined

本文转自:https://stackoverflow.com/questions/39755336/angular2-cannot-read-property-name-of-undefined

 

处理方式1:

The variable selectedHero is null in the template so you cannot bind selectedHero.name as is. You need to use the elvis operator for this case:


The separation of the [(ngModel)] in [ngModel] and (ngModelChange) is also needed because you can't assign to an expression that uses the elvis operator.

I also think you mean to use:

{{selectedHero?.name}} details!

instead of:

{{hero.name}} details!





处理方式2:

You just needed to read a little further and you would have been introduced to the *ngIf structural directive.

selectedHero.name doesn't exist yet because the user has yet to select a hero so it returns undefined.

 *ngIf="selectedHero">
  

{{selectedHero.name}} details!

{{selectedHero.id}}

The *ngIf directive keeps selectedHero off the DOM until it is selected and therefore becomes truthy.

This document helped me understand structural directives.

 

你可能感兴趣的:([转]Angular2: Cannot read property 'name' of undefined)