码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2018-09-29 10:17:09      阅读:317      评论:0      收藏:0      [点我收藏+]

标签: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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!