1. 程式人生 > >[轉]Angular2: Cannot read property 'name' of undefined

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

struct mes use efi html detail event blank truct

本文轉自: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:

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

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:

<h2>{{selectedHero?.name}} details!</h2>

instead of:

<h2>{{hero.name}} details!</h2>



處理方式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.

<div *ngIf="selectedHero">
  <h2>{{selectedHero.name}} details!</h2>
  <div><label>id: </label>{{selectedHero.id}}</div>
  <div>
    <label>name: </label>
    <input [(ngModel)]="selectedHero.name" placeholder="name"/>
  </div>
</div>

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