Angular4:无法读取undefined的属性 [英] Angular4: cannot read the property of undefined
本文介绍了Angular4:无法读取undefined的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用他们在网站上提供的教程学习angular4
I am trying to learn angular4 with the tutorial they provided in website
这是代码
hero.ts
export class Hero{
constructor(
public id: number,public name: string
){}
}
in component.ts
import { Component } from '@angular/core';
import {Hero } from './hero';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title : string;
hero : string;
selectedHero: Hero;
heroes = [
new Hero(1, 'Windstorm'),
new Hero(13, 'Bombasto'),
new Hero(15, 'Magneta'),
new Hero(20, 'Tornado')
]
myHero = this.heroes[0];
constructor(){
this.title = 'Tour of heros';
}
onSelect(hero: Hero): void {
this.selectedHero =hero;
}
}
html
<ul>
<li *ngFor="let hero of heroes" (click)="onSelect(hero)">
{{ hero.name }}
</li>
</ul>
<p>{{selectedHero.name}}</p>
点击每个 li
我想要显示所选对象的详细信息,但我收到以下错误
when click on each li
i would like to display details in selected object but i got the following error
selectedHero.name
未定义
推荐答案
如果在访问任何属性之前设置了selectedHero,则签入模板
Check in the template if selectedHero is set before access any of its property
<p *ngIf="selectedHero">{{selectedHero.name}}</p>
或在组件中创建一个空实例(更新后的答案)
or create an empty instance in the component (updated answer)
selectedHero: Hero = new Hero(12, 'somename');
这篇关于Angular4:无法读取undefined的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文