Angular2:无法读取未定义的属性“名称" [英] Angular2: Cannot read property 'name' of undefined

查看:143
本文介绍了Angular2:无法读取未定义的属性“名称"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始学习Angular2.我一直在关注angular.io提供的《英雄教程》. 一切工作正常,直到被使用模板的HTML弄得一团糟,我使用模板URL代替了它,并将HTML移到了一个名为hero.html的文件中. 生成的错误是,无法读取未定义的属性'名称'". 奇怪的是,可以访问指向对象数组的heroes变量,以便ngFor根据数组中对象的数量生成正确数量的"li"标签.但是,无法访问数组对象的数据. 此外,即使是包含一些文本的简单变量,也不会在HTML中使用{{}}括号显示(请参见提供的代码).

I am beginning to learn Angular2. I've been following the Heroes Tutorial provided at angular.io. All was working fine until, being annoyed by the clutter of HTML using the template, I used template URL in its place, and moved the HTML to a file named hero.html. The error that is generated is, "Cannot read property 'name' of undefined". Strangely, the heroes variable which points to an array of objects can be accessed so that ngFor will produce the correct amount of "li" tags according to the number of objects in the array. However, the data of the objects of the array cannot be accessed. Furthermore, even a simple variable holding some text, will not display using {{}} brackets in the HTML (see provided code).

app.component.ts

app.component.ts

import { Component } from '@angular/core';
@Component({
  selector: 'my-app',
  templateUrl: './hero.html',
  styleUrls:['./styles.css']
})

export class AppComponent {
  title = 'Tour of Heroes';
  heroes = HEROES;
  selectedHero:Hero;

  onSelect(hero: Hero):void{
      this.selectedHero = hero;
  }
}

export class Hero{
   id: number;
   name: string;
}

const HEROES: Hero[] = [
   { id: 1, name: 'Mr. Nice' },
   { id: 2, name: 'Narco' },
   { id: 3, name: 'Bombasto' },
   { id: 4, name: 'Celeritas' },
   { id: 5, name: 'Magneta' },
   { id: 6, name: 'RubberMan' },
   { id: 7, name: 'Dynama' },
   { id: 8, name: 'Dr IQ' },
   { id: 9, name: 'Magma' },
   { id: 10, name: 'Tornado' }
];

hero.html

hero.html

<h1>{{title}}</h1>
<h2>My Heroes</h2>
<ul class="heroes">
  <li *ngFor="let hero of heroes">
    <span class="badge">{{hero.id}}</span> {{hero.name}}
  </li>
</ul>
<h2>{{hero.name}} details!</h2>
<div>
    <label>id: </label>{{hero.id}}
</div>
<div>
    <label>name: </label>
    <input [(ngModel)]="selectedHero.name" placeholder="name">
<div>

这是一张照片:

推荐答案

模板中的selectedHero变量为null,因此无法按原样绑定selectedHero.name.在这种情况下,您需要使用elvis运算符:

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" />

还需要将[ngModel]中的[(ngModel)]和(ngModelChange)分开,因为您不能将其分配给使用elvis运算符的表达式.

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.

我还认为您打算使用:

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

代替:

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

这篇关于Angular2:无法读取未定义的属性“名称"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆