标签:ide property his use NPU think gif tle document
本文转自: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
标签:ide property his use NPU think gif tle document
原文地址:https://www.cnblogs.com/freeliver54/p/9722004.html